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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.774   ! raeburn     4: # $Id: grades.pm,v 1.773 2020/08/30 20:30:21 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>';
                    296:     return $result;
                    297: }
                    298: 
                    299: sub part_selector_js {
                    300:     my $js = <<"END";
                    301: function toggleParts(formname) {
                    302:     if (document.getElementById('LC_partselector')) {
                    303:         var index = '';
                    304:         if (document.forms.length) {
                    305:             for (var i=0; i<document.forms.length; i++) {
                    306:                 if (document.forms[i].name == formname) {
                    307:                     index = i;
                    308:                     break;
                    309:                 }
                    310:             }
                    311:         }
                    312:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    313:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    314:                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    315:                    var val = document.forms[index].elements['chooseparts'][i].value;
                    316:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    317:                         document.getElementById('LC_partselector').style.display = 'block';
                    318:                     } else {
                    319:                         document.getElementById('LC_partselector').style.display = 'none';
                    320:                     }
                    321:                 }
                    322:             }
                    323:         }
                    324:     }
                    325: }
                    326: END
                    327:     return &Apache::lonhtmlcommon::scripttag($js);
                    328: }
                    329: 
1.434     albertel  330: sub reset_caches {
                    331:     &reset_analyze_cache();
                    332:     &reset_perm();
1.674     raeburn   333:     &reset_old_essays();
1.434     albertel  334: }
                    335: 
                    336: {
                    337:     my %analyze_cache;
1.557     raeburn   338:     my %analyze_cache_formkeys;
1.148     albertel  339: 
1.434     albertel  340:     sub reset_analyze_cache {
                    341: 	undef(%analyze_cache);
1.557     raeburn   342:         undef(%analyze_cache_formkeys);
1.434     albertel  343:     }
                    344: 
                    345:     sub get_analyze {
1.649     raeburn   346: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  347: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   348:         if ($type eq 'randomizetry') {
                    349:             if ($trial ne '') {
                    350:                 $key .= "\0".$trial;
                    351:             }
                    352:         }
1.557     raeburn   353: 	if (exists($analyze_cache{$key})) {
                    354:             my $getupdate = 0;
                    355:             if (ref($add_to_hash) eq 'HASH') {
                    356:                 foreach my $item (keys(%{$add_to_hash})) {
                    357:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    358:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    359:                             $getupdate = 1;
                    360:                             last;
                    361:                         }
                    362:                     } else {
                    363:                         $getupdate = 1;
                    364:                     }
                    365:                 }
                    366:             }
                    367:             if (!$getupdate) {
                    368:                 return $analyze_cache{$key};
                    369:             }
                    370:         }
1.434     albertel  371: 
                    372: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    373: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   374:         my %form = ('grade_target'      => 'analyze',
                    375:                     'grade_domain'      => $udom,
                    376:                     'grade_symb'        => $symb,
                    377:                     'grade_courseid'    =>  $env{'request.course.id'},
                    378:                     'grade_username'    => $uname,
                    379:                     'grade_noincrement' => $no_increment);
1.649     raeburn   380:         if ($bubbles_per_row ne '') {
                    381:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    382:         }
1.640     raeburn   383:         if ($type eq 'randomizetry') {
                    384:             $form{'grade_questiontype'} = $type;
                    385:             if ($rndseed ne '') {
                    386:                 $form{'grade_rndseed'} = $rndseed;
                    387:             }
                    388:         }
1.557     raeburn   389:         if (ref($add_to_hash)) {
                    390:             %form = (%form,%{$add_to_hash});
1.640     raeburn   391:         }
1.557     raeburn   392: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  393: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    394: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   395:         if (ref($add_to_hash) eq 'HASH') {
                    396:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    397:         } else {
                    398:             $analyze_cache_formkeys{$key} = {};
                    399:         }
1.434     albertel  400: 	return $analyze_cache{$key} = \%analyze;
                    401:     }
                    402: 
                    403:     sub get_order {
1.640     raeburn   404: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    405: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  406: 	return $analyze->{"$partid.$respid.shown"};
                    407:     }
                    408: 
                    409:     sub get_radiobutton_correct_foil {
1.640     raeburn   410: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    411: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    412:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   413:         if (ref($foils) eq 'ARRAY') {
                    414: 	    foreach my $foil (@{$foils}) {
                    415: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    416: 		    return $foil;
                    417: 	        }
1.434     albertel  418: 	    }
                    419: 	}
                    420:     }
1.554     raeburn   421: 
                    422:     sub scantron_partids_tograde {
1.741     raeburn   423:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   424:         my (%analysis,@parts);
                    425:         if (ref($resource)) {
                    426:             my $symb = $resource->symb();
1.557     raeburn   427:             my $add_to_form;
                    428:             if ($check_for_randomlist) {
                    429:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    430:             }
1.741     raeburn   431:             if ($scancode) {
                    432:                 if (ref($add_to_form) eq 'HASH') {
                    433:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    434:                 } else {
                    435:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    436:                 }
                    437:             }
1.767     raeburn   438:             my $analyze =
1.649     raeburn   439:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    440:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   441:             if (ref($analyze) eq 'HASH') {
                    442:                 %analysis = %{$analyze};
                    443:             }
                    444:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    445:                 foreach my $part (@{$analysis{'parts'}}) {
                    446:                     my ($id,$respid) = split(/\./,$part);
                    447:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    448:                         push(@parts,$part);
                    449:                     }
                    450:                 }
                    451:             }
                    452:         }
                    453:         return (\%analysis,\@parts);
                    454:     }
                    455: 
1.148     albertel  456: }
1.434     albertel  457: 
1.118     ng        458: #--- Clean response type for display
1.335     albertel  459: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    460: #        response types only.
1.118     ng        461: sub cleanRecord {
1.336     albertel  462:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   463: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  464:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  465:     if ($response =~ /^(option|rank)$/) {
                    466: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     467:         my @answer = %answer;
1.767     raeburn   468:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  469: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    470: 	my ($toprow,$bottomrow);
                    471: 	foreach my $foil (@$order) {
                    472: 	    if ($grading{$foil} == 1) {
                    473: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    474: 	    } else {
                    475: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    476: 	    }
1.398     albertel  477: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  478: 	}
                    479: 	return '<blockquote><table border="1">'.
1.466     albertel  480: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    481: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   482: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  483:     } elsif ($response eq 'match') {
                    484: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     485:         my @answer = %answer;
1.767     raeburn   486:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  487: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    488: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    489: 	my ($toprow,$middlerow,$bottomrow);
                    490: 	foreach my $foil (@$order) {
                    491: 	    my $item=shift(@items);
                    492: 	    if ($grading{$foil} == 1) {
                    493: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  494: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  495: 	    } else {
                    496: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  497: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  498: 	    }
1.398     albertel  499: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        500: 	}
1.126     ng        501: 	return '<blockquote><table border="1">'.
1.466     albertel  502: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    503: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  504: 	    $middlerow.'</tr>'.
1.466     albertel  505: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   506: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  507:     } elsif ($response eq 'radiobutton') {
                    508: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     509:         my @answer = %answer;
                    510:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  511: 	my ($toprow,$bottomrow);
1.434     albertel  512: 	my $correct = 
1.640     raeburn   513: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  514: 	foreach my $foil (@$order) {
1.148     albertel  515: 	    if (exists($answer{$foil})) {
1.434     albertel  516: 		if ($foil eq $correct) {
1.466     albertel  517: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  518: 		} else {
1.466     albertel  519: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  520: 		}
                    521: 	    } else {
1.466     albertel  522: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  523: 	    }
1.398     albertel  524: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  525: 	}
                    526: 	return '<blockquote><table border="1">'.
1.466     albertel  527: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    528: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   529: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  530:     } elsif ($response eq 'essay') {
1.257     albertel  531: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        532: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  533: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    534: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        535: 
1.257     albertel  536: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    537: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    538: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    539: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    540: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    541: 	    $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        542: 	}
1.751     raeburn   543:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     544: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  545:     } elsif ( $response eq 'organic') {
1.721     bisitz    546:         my $result=&mt('Smile representation: [_1]',
                    547:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  548: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    549: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    550: 	return $result;
1.335     albertel  551:     } elsif ( $response eq 'Task') {
                    552: 	if ( $answer eq 'SUBMITTED') {
                    553: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  554: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  555: 	    return $result;
                    556: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    557: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    558: 			       keys(%{$record}));
                    559: 	    return join('<br />',($version,@matches));
                    560: 			       
                    561: 			       
                    562: 	} else {
                    563: 	    my $result =
                    564: 		'<p>'
                    565: 		.&mt('Overall result: [_1]',
                    566: 		     $record->{$version."resource.$respid.$partid.status"})
                    567: 		.'</p>';
                    568: 	    
                    569: 	    $result .= '<ul>';
                    570: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    571: 			     keys(%{$record}));
                    572: 	    foreach my $grade (sort(@grade)) {
                    573: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    574: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    575: 				     $dim, $record->{$grade}).
                    576: 			  '</li>';
                    577: 	    }
                    578: 	    $result.='</ul>';
                    579: 	    return $result;
                    580: 	}
1.716     bisitz    581:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    582:         # Respect multiple input fields, see Bug #5409
1.440     albertel  583: 	$answer = 
                    584: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    585: 							      $answer);
1.720     kruse     586: 	return $answer;
1.122     ng        587:     }
1.720     kruse     588:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        589: }
                    590: 
                    591: #-- A couple of common js functions
                    592: sub commonJSfunctions {
                    593:     my $request = shift;
1.597     wenzelju  594:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        595:     function radioSelection(radioButton) {
                    596: 	var selection=null;
                    597: 	if (radioButton.length > 1) {
                    598: 	    for (var i=0; i<radioButton.length; i++) {
                    599: 		if (radioButton[i].checked) {
                    600: 		    return radioButton[i].value;
                    601: 		}
                    602: 	    }
                    603: 	} else {
                    604: 	    if (radioButton.checked) return radioButton.value;
                    605: 	}
                    606: 	return selection;
                    607:     }
                    608: 
                    609:     function pullDownSelection(selectOne) {
                    610: 	var selection="";
                    611: 	if (selectOne.length > 1) {
                    612: 	    for (var i=0; i<selectOne.length; i++) {
                    613: 		if (selectOne[i].selected) {
                    614: 		    return selectOne[i].value;
                    615: 		}
                    616: 	    }
                    617: 	} else {
1.138     albertel  618:             // only one value it must be the selected one
                    619: 	    return selectOne.value;
1.118     ng        620: 	}
                    621:     }
                    622: COMMONJSFUNCTIONS
                    623: }
                    624: 
1.44      ng        625: #--- Dumps the class list with usernames,list of sections,
                    626: #--- section, ids and fullnames for each user.
                    627: sub getclasslist {
1.750     raeburn   628:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  629:     my @getsec;
1.450     banghart  630:     my @getgroup;
1.442     banghart  631:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  632:     if (!ref($getsec)) {
                    633: 	if ($getsec ne '' && $getsec ne 'all') {
                    634: 	    @getsec=($getsec);
                    635: 	}
                    636:     } else {
                    637: 	@getsec=@{$getsec};
                    638:     }
                    639:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  640:     if (!ref($getgroup)) {
                    641: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    642: 	    @getgroup=($getgroup);
                    643: 	}
                    644:     } else {
                    645: 	@getgroup=@{$getgroup};
                    646:     }
                    647:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  648: 
1.449     banghart  649:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  650:     # Bail out if we were unable to get the classlist
1.56      matthew   651:     return if (! defined($classlist));
1.449     banghart  652:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   653:     #
                    654:     my %sections;
                    655:     my %fullnames;
1.750     raeburn   656:     my ($cdom,$cnum,$partlist);
                    657:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    658:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    659:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    660:         my $res_error;
1.773     raeburn   661:         ($partlist) = &response_type($symb,\$res_error);
1.750     raeburn   662:     }
1.205     matthew   663:     foreach my $student (keys(%$classlist)) {
                    664:         my $end      = 
                    665:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    666:         my $start    = 
                    667:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    668:         my $id       = 
                    669:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    670:         my $section  = 
                    671:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    672:         my $fullname = 
                    673:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    674:         my $status   = 
                    675:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  676:         my $group   = 
                    677:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        678: 	# filter students according to status selected
1.750     raeburn   679: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  680: 	    if (!($stu_status =~ $status)) {
1.450     banghart  681: 		delete($classlist->{$student});
1.76      ng        682: 		next;
                    683: 	    }
                    684: 	}
1.450     banghart  685: 	# filter students according to groups selected
1.453     banghart  686: 	my @stu_groups = split(/,/,$group);
1.450     banghart  687: 	if (@getgroup) {
                    688: 	    my $exclude = 1;
1.454     banghart  689: 	    foreach my $grp (@getgroup) {
                    690: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  691: 	            if ($stu_group eq $grp) {
                    692: 	                $exclude = 0;
                    693:     	            } 
1.450     banghart  694: 	        }
1.453     banghart  695:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   696:         	    $exclude = 0;
1.453     banghart  697:         	}
1.450     banghart  698: 	    }
                    699: 	    if ($exclude) {
                    700: 	        delete($classlist->{$student});
1.750     raeburn   701: 		next;
1.450     banghart  702: 	    }
                    703: 	}
1.750     raeburn   704:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    705:             my $udom =
                    706:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    707:             my $uname =
                    708:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    709:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    710:                 if ($submitonly eq 'queued') {
                    711:                     my %queue_status =
                    712:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    713:                                                                 $udom,$uname);
                    714:                     if (!defined($queue_status{'gradingqueue'})) {
                    715:                         delete($classlist->{$student});
                    716:                         next;
                    717:                     }
                    718:                 } else {
                    719:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    720:                     my $submitted = 0;
                    721:                     my $graded = 0;
                    722:                     my $incorrect = 0;
                    723:                     foreach (keys(%status)) {
                    724:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    725:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    726:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    727: 
                    728:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    729:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    730:                             $submitted = 0;
                    731:                         }
                    732:                     }
                    733:                     if (!$submitted && ($submitonly eq 'yes' ||
                    734:                                         $submitonly eq 'incorrect' ||
                    735:                                         $submitonly eq 'graded')) {
                    736:                         delete($classlist->{$student});
                    737:                         next;
                    738:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    739:                         delete($classlist->{$student});
                    740:                         next;
                    741:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    742:                         delete($classlist->{$student});
                    743:                         next;
                    744:                     }
                    745:                 }
                    746:             }
                    747:         }
1.205     matthew   748: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  749: 	if (&canview($section)) {
1.291     albertel  750: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  751: 		$sections{$section}++;
1.450     banghart  752: 		if ($classlist->{$student}) {
                    753: 		    $fullnames{$student}=$fullname;
                    754: 		}
1.103     albertel  755: 	    } else {
1.205     matthew   756: 		delete($classlist->{$student});
1.103     albertel  757: 	    }
                    758: 	} else {
1.205     matthew   759: 	    delete($classlist->{$student});
1.103     albertel  760: 	}
1.44      ng        761:     }
1.56      matthew   762:     my @sections = sort(keys(%sections));
                    763:     return ($classlist,\@sections,\%fullnames);
1.44      ng        764: }
                    765: 
1.103     albertel  766: sub canmodify {
                    767:     my ($sec)=@_;
                    768:     if ($perm{'mgr'}) {
                    769: 	if (!defined($perm{'mgr_section'})) {
                    770: 	    # can modify whole class
                    771: 	    return 1;
                    772: 	} else {
                    773: 	    if ($sec eq $perm{'mgr_section'}) {
                    774: 		#can modify the requested section
                    775: 		return 1;
                    776: 	    } else {
1.763     raeburn   777: 		# can't modify the requested section
1.103     albertel  778: 		return 0;
                    779: 	    }
                    780: 	}
                    781:     }
                    782:     #can't modify
                    783:     return 0;
                    784: }
                    785: 
                    786: sub canview {
                    787:     my ($sec)=@_;
                    788:     if ($perm{'vgr'}) {
                    789: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   790: 	    # can view whole class
1.103     albertel  791: 	    return 1;
                    792: 	} else {
                    793: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   794: 		#can view the requested section
1.103     albertel  795: 		return 1;
                    796: 	    } else {
1.763     raeburn   797: 		# can't view the requested section
1.103     albertel  798: 		return 0;
                    799: 	    }
                    800: 	}
                    801:     }
1.763     raeburn   802:     #can't view
1.103     albertel  803:     return 0;
                    804: }
                    805: 
1.44      ng        806: #--- Retrieve the grade status of a student for all the parts
                    807: sub student_gradeStatus {
1.324     albertel  808:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  809:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        810:     my %partstatus = ();
                    811:     foreach (@$partlist) {
1.128     ng        812: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        813: 	$status              = 'nothing' if ($status eq '');
                    814: 	$partstatus{$_}      = $status;
                    815: 	my $subkey           = "resource.$_.submitted_by";
                    816: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    817:     }
                    818:     return %partstatus;
                    819: }
                    820: 
1.45      ng        821: # hidden form and javascript that calls the form
                    822: # Use by verifyscript and viewgrades
                    823: # Shows a student's view of problem and submission
                    824: sub jscriptNform {
1.324     albertel  825:     my ($symb) = @_;
1.442     banghart  826:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  827:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        828: 	'    function viewOneStudent(user,domain) {'."\n".
                    829: 	'	document.onestudent.student.value = user;'."\n".
                    830: 	'	document.onestudent.userdom.value = domain;'."\n".
                    831: 	'	document.onestudent.submit();'."\n".
                    832: 	'    }'."\n".
1.597     wenzelju  833: 	"\n");
1.45      ng        834:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  835: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  836: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        837: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    838: 	'<input type="hidden" name="student" value="" />'."\n".
                    839: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    840: 	'</form>'."\n";
                    841:     return $jscript;
                    842: }
1.39      ng        843: 
1.447     foxr      844: 
                    845: 
1.315     bowersj2  846: # Given the score (as a number [0-1] and the weight) what is the final
                    847: # point value? This function will round to the nearest tenth, third,
                    848: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  849: sub compute_points {
1.315     bowersj2  850:     my ($score, $weight) = @_;
                    851:     
                    852:     my $tolerance = .00001;
                    853:     my $points = $score * $weight;
                    854: 
                    855:     # Check for nearness to 1/x.
                    856:     my $check_for_nearness = sub {
                    857:         my ($factor) = @_;
                    858:         my $num = ($points * $factor) + $tolerance;
                    859:         my $floored_num = floor($num);
1.316     albertel  860:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  861:             return $floored_num / $factor;
                    862:         }
                    863:         return $points;
                    864:     };
                    865: 
                    866:     $points = $check_for_nearness->(10);
                    867:     $points = $check_for_nearness->(3);
                    868:     $points = $check_for_nearness->(4);
                    869:     
                    870:     return $points;
                    871: }
                    872: 
1.44      ng        873: #------------------ End of general use routines --------------------
1.87      www       874: 
                    875: #
                    876: # Find most similar essay
                    877: #
                    878: 
                    879: sub most_similar {
1.674     raeburn   880:     my ($uname,$udom,$symb,$uessay)=@_;
                    881: 
                    882:     unless ($symb) { return ''; }
                    883: 
                    884:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       885: 
                    886: # ignore spaces and punctuation
                    887: 
                    888:     $uessay=~s/\W+/ /gs;
                    889: 
1.282     www       890: # ignore empty submissions (occuring when only files are sent)
                    891: 
1.598     www       892:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       893: 
1.87      www       894: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       895:     my $limit=0.6;
1.87      www       896:     my $sname='';
                    897:     my $sdom='';
                    898:     my $scrsid='';
                    899:     my $sessay='';
                    900: # go through all essays ...
1.674     raeburn   901:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  902: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       903: # ... except the same student
1.426     albertel  904:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   905: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  906: 	$tessay=~s/\W+/ /gs;
1.87      www       907: # String similarity gives up if not even limit
1.426     albertel  908: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       909: # Found one
1.426     albertel  910: 	if ($tsimilar>$limit) {
                    911: 	    $limit=$tsimilar;
                    912: 	    $sname=$tname;
                    913: 	    $sdom=$tdom;
                    914: 	    $scrsid=$tcrsid;
1.674     raeburn   915: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  916: 	}
1.87      www       917:     }
1.88      www       918:     if ($limit>0.6) {
1.87      www       919:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    920:     } else {
                    921:        return ('','','','',0);
                    922:     }
                    923: }
                    924: 
1.44      ng        925: #-------------------------------------------------------------------
                    926: 
                    927: #------------------------------------ Receipt Verification Routines
1.45      ng        928: #
1.602     www       929: 
                    930: sub initialverifyreceipt {
1.608     www       931:    my ($request,$symb) = @_;
1.602     www       932:    &commonJSfunctions($request);
1.694     bisitz    933:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       934:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    935:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       936:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    937:         '<input type="hidden" name="command" value="verify" />'.
                    938:         "</form>\n";
1.602     www       939: }
                    940: 
1.44      ng        941: #--- Check whether a receipt number is valid.---
                    942: sub verifyreceipt {
1.766     raeburn   943:     my ($request,$symb) = @_;
1.44      ng        944: 
1.257     albertel  945:     my $courseid = $env{'request.course.id'};
1.184     www       946:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  947: 	$env{'form.receipt'};
1.44      ng        948:     $receipt     =~ s/[^\-\d]//g;
                    949: 
1.766     raeburn   950:     my $title =
1.487     albertel  951: 	'<h3><span class="LC_info">'.
1.605     www       952: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    953: 	'</span></h3>'."\n";
1.44      ng        954: 
                    955:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   956:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  957:     
                    958:     my $receiptparts=0;
1.390     albertel  959:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    960: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  961:     my $parts=['0'];
1.582     raeburn   962:     if ($receiptparts) {
                    963:         my $res_error; 
                    964:         ($parts)=&response_type($symb,\$res_error);
                    965:         if ($res_error) {
                    966:             return &navmap_errormsg();
                    967:         } 
                    968:     }
1.486     albertel  969:     
                    970:     my $header = 
                    971: 	&Apache::loncommon::start_data_table().
                    972: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  973: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    974: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    975: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  976:     if ($receiptparts) {
1.487     albertel  977: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  978:     }
                    979:     $header.=
                    980: 	&Apache::loncommon::end_data_table_header_row();
                    981: 
1.294     albertel  982:     foreach (sort 
                    983: 	     {
                    984: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    985: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    986: 		 }
                    987: 		 return $a cmp $b;
                    988: 	     } (keys(%$fullname))) {
1.44      ng        989: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  990: 	foreach my $part (@$parts) {
                    991: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  992: 		$contents.=
                    993: 		    &Apache::loncommon::start_data_table_row().
                    994: 		    '<td>&nbsp;'."\n".
1.177     albertel  995: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  996: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  997: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    998: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    999: 		if ($receiptparts) {
                   1000: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1001: 		}
1.486     albertel 1002: 		$contents.= 
                   1003: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1004: 		
                   1005: 		$matches++;
                   1006: 	    }
1.44      ng       1007: 	}
                   1008:     }
                   1009:     if ($matches == 0) {
1.584     bisitz   1010:         $string = $title
                   1011:                  .'<p class="LC_warning">'
                   1012:                  .&mt('No match found for the above receipt number.')
                   1013:                  .'</p>';
1.44      ng       1014:     } else {
1.324     albertel 1015: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1016: 	    '<p>'.
1.584     bisitz   1017: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1018: 	    '</p>'.
1.486     albertel 1019: 	    $header.
                   1020: 	    $contents.
                   1021: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1022:     }
1.614     www      1023:     return $string;
1.44      ng       1024: }
                   1025: 
                   1026: #--- This is called by a number of programs.
                   1027: #--- Called from the Grading Menu - View/Grade an individual student
                   1028: #--- Also called directly when one clicks on the subm button 
                   1029: #    on the problem page.
1.30      ng       1030: sub listStudents {
1.773     raeburn  1031:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1032: 
1.747     raeburn  1033:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1034:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1035:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1036:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1037:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1038:     unless ($submitonly) {
1.766     raeburn  1039:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1040:     }
1.49      albertel 1041: 
1.632     www      1042:     my $result='';
1.623     www      1043:     my $res_error;
1.773     raeburn  1044:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   1045: 
                   1046:     my $table;
                   1047:     if (ref($partlist) eq 'ARRAY') {
                   1048:         if (scalar(@$partlist) > 1 ) {
                   1049:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1050:         } elsif ($divforres) {
                   1051:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1052:         } else {
                   1053:             $table = '<br clear="all" />';
                   1054:         }
                   1055:     }
1.49      albertel 1056: 
1.736     damieng  1057:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1058: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1059: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1060: 	     );
1.736     damieng  1061:     &js_escape(\%js_lt);
1.597     wenzelju 1062:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1063:     function checkSelect(checkBox) {
                   1064: 	var ctr=0;
                   1065: 	var sense="";
                   1066: 	if (checkBox.length > 1) {
                   1067: 	    for (var i=0; i<checkBox.length; i++) {
                   1068: 		if (checkBox[i].checked) {
                   1069: 		    ctr++;
                   1070: 		}
                   1071: 	    }
1.736     damieng  1072: 	    sense = '$js_lt{'multiple'}';
1.110     ng       1073: 	} else {
                   1074: 	    if (checkBox.checked) {
                   1075: 		ctr = 1;
                   1076: 	    }
1.736     damieng  1077: 	    sense = '$js_lt{'single'}';
1.110     ng       1078: 	}
                   1079: 	if (ctr == 0) {
1.485     albertel 1080: 	    alert(sense);
1.110     ng       1081: 	    return false;
                   1082: 	}
                   1083: 	document.gradesub.submit();
                   1084:     }
                   1085: 
                   1086:     function reLoadList(formname) {
1.112     ng       1087: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1088: 	formname.command.value = 'submission';
                   1089: 	formname.submit();
                   1090:     }
1.45      ng       1091: LISTJAVASCRIPT
                   1092: 
1.118     ng       1093:     &commonJSfunctions($request);
1.41      ng       1094:     $request->print($result);
1.39      ng       1095: 
1.154     albertel 1096:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773     raeburn  1097: 	"\n".$table;
                   1098: 
1.561     bisitz   1099:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1100:     unless ($is_tool) {
                   1101:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1102:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1103:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1104:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1105:                       .&Apache::lonhtmlcommon::row_closure();
                   1106:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1107:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1108:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1109:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1110:                       .&Apache::lonhtmlcommon::row_closure();
                   1111:     }
1.485     albertel 1112: 
1.442     banghart 1113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1114:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1115:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1116:     my %optiontext;
                   1117:     if ($is_tool) {
                   1118:         %optiontext = &Apache::lonlocal::texthash (
                   1119:                           lastonly => 'last transaction',
                   1120:                           last     => 'last transaction with details',
                   1121:                           datesub  => 'all transactions',
                   1122:                           all      => 'all transactions with details',
                   1123:                       );
                   1124:     } else {
                   1125:         %optiontext = &Apache::lonlocal::texthash (
                   1126:                           lastonly => 'last submission',
                   1127:                           last     => 'last submission with details',
                   1128:                           datesub  => 'all submissions',
                   1129:                           all      => 'all submissions with details',
                   1130:                       );
                   1131:     }
1.773     raeburn  1132:     my $submission_options =
1.592     bisitz   1133:         '<span class="LC_nobreak">'.
1.624     www      1134:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1135:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1136:         '<span class="LC_nobreak">'.
                   1137:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1138:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1139:         '<span class="LC_nobreak">'.
1.628     www      1140:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1141:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1142:         '<span class="LC_nobreak">'.
                   1143:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1144:         $optiontext{'all'}.'</label></span>';
                   1145:     my $viewtitle;
                   1146:     if ($is_tool) {
                   1147:         $viewtitle = &mt('View Transactions');
                   1148:     } else {
                   1149:         $viewtitle = &mt('View Submissions');
                   1150:     }
1.773     raeburn  1151:     my ($compmsg,$nocompmsg);
                   1152:     $nocompmsg = ' checked="checked"';
                   1153:     if ($numessay) {
                   1154:         $compmsg = $nocompmsg;
                   1155:         $nocompmsg = '';
                   1156:     }
1.745     raeburn  1157:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1158:                   .$submission_options
1.773     raeburn  1159:                   .&Apache::lonhtmlcommon::row_closure()
                   1160:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1161:                   .'<span class="LC_nobreak">'
                   1162:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1163:                   .&mt('No').('&nbsp;'x2).'</label>'
                   1164:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1165:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1166:                   .&Apache::lonhtmlcommon::row_closure();
                   1167: 
                   1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1169:                   .'<select name="increment">'
                   1170:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1171:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1172:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1173:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773     raeburn  1174:                   .'</select>';
1.485     albertel 1175:     $gradeTable .= 
1.432     banghart 1176:         &build_section_inputs().
1.45      ng       1177: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1178: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1179: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1180:     if (exists($env{'form.Status'})) {
1.561     bisitz   1181: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1182:     } else {
1.773     raeburn  1183:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1184:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1185:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773     raeburn  1186:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1187:     }
1.773     raeburn  1188:     if ($numessay) {
                   1189:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1190:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1191:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1192:     }
1.773     raeburn  1193:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
                   1194:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1195:     my $regrademsg;
                   1196:     if ($is_tool) {
                   1197:         $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.");
                   1198:     } else {
                   1199:         $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.");
                   1200:     }
1.561     bisitz   1201:     $gradeTable .= '<p>'
1.745     raeburn  1202:                   .$regrademsg."\n"
1.561     bisitz   1203:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1204:                   .'</p>';
1.249     albertel 1205: 
                   1206: # checkall buttons
                   1207:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1208:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1209:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1210:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1211:     $gradeTable.=&check_buttons();
1.450     banghart 1212:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1213:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1214: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1215:     my $loop = 0;
                   1216:     while ($loop < 2) {
1.485     albertel 1217: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1218: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1219: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1220: 	    foreach my $part (sort(@$partlist)) {
                   1221: 		my $display_part=
                   1222: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1223: 		$gradeTable.=
                   1224: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1225: 	    }
1.301     albertel 1226: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1227: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1228: 	}
                   1229: 	$loop++;
1.126     ng       1230: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1231:     }
1.474     albertel 1232:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1233: 
1.45      ng       1234:     my $ctr = 0;
1.294     albertel 1235:     foreach my $student (sort 
                   1236: 			 {
                   1237: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1238: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1239: 			     }
                   1240: 			     return $a cmp $b;
                   1241: 			 }
                   1242: 			 (keys(%$fullname))) {
1.41      ng       1243: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1244: 
1.110     ng       1245: 	my %status = ();
1.301     albertel 1246: 
                   1247: 	if ($submitonly eq 'queued') {
                   1248: 	    my %queue_status = 
                   1249: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1250: 							$udom,$uname);
                   1251: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1252: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1253: 	}
                   1254: 
1.618     www      1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1256: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1257: 	    my $submitted = 0;
1.164     albertel 1258: 	    my $graded = 0;
1.248     albertel 1259: 	    my $incorrect = 0;
1.110     ng       1260: 	    foreach (keys(%status)) {
1.145     albertel 1261: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1262: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1263: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1264: 		
1.110     ng       1265: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1266: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1267: 		    $submitted = 0;
1.150     albertel 1268: 		    my ($part)=split(/\./,$partid);
1.110     ng       1269: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1270: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1271: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1272: 		}
1.41      ng       1273: 	    }
1.248     albertel 1274: 	    
1.156     albertel 1275: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1276: 				     $submitonly eq 'incorrect' ||
                   1277: 				     $submitonly eq 'graded'));
1.248     albertel 1278: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1279: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1280: 	}
1.34      ng       1281: 
1.45      ng       1282: 	$ctr++;
1.249     albertel 1283: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1284:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1285: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1286: 	    if ($ctr%2 ==1) {
                   1287: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1288: 	    }
1.126     ng       1289: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1290:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1291:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1292: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1293: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1294: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1295: 
1.618     www      1296: 	    if ($submitonly ne 'all') {
1.524     raeburn  1297: 		foreach (sort(keys(%status))) {
1.485     albertel 1298: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1299: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1300: 		}
1.41      ng       1301: 	    }
1.126     ng       1302: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1303: 	    if ($ctr%2 ==0) {
                   1304: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1305: 	    }
1.41      ng       1306: 	}
                   1307:     }
1.110     ng       1308:     if ($ctr%2 ==1) {
1.126     ng       1309: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1310: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1311: 		foreach (@$partlist) {
                   1312: 		    $gradeTable.='<td>&nbsp;</td>';
                   1313: 		}
1.301     albertel 1314: 	    } elsif ($submitonly eq 'queued') {
                   1315: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1316: 	    }
1.474     albertel 1317: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1318:     }
                   1319: 
1.474     albertel 1320:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1321:         '<input type="button" '.
                   1322:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1323:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1324:     if ($ctr == 0) {
1.96      albertel 1325: 	my $num_students=(scalar(keys(%$fullname)));
                   1326: 	if ($num_students eq 0) {
1.485     albertel 1327: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1328: 	} else {
1.171     albertel 1329: 	    my $submissions='submissions';
                   1330: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1331: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1332: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1333: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1334: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1335: 		    $num_students).
                   1336: 		'</span><br />';
1.96      albertel 1337: 	}
1.46      ng       1338:     } elsif ($ctr == 1) {
1.474     albertel 1339: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1340:     }
                   1341:     $request->print($gradeTable);
1.44      ng       1342:     return '';
1.10      ng       1343: }
                   1344: 
1.44      ng       1345: #---- Called from the listStudents routine
1.249     albertel 1346: 
                   1347: sub check_script {
1.766     raeburn  1348:     my ($form,$type) = @_;
                   1349:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1350:     function checkall() {
                   1351:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1352:             ele = document.forms.'.$form.'.elements[i];
                   1353:             if (ele.name == "'.$type.'") {
                   1354:             document.forms.'.$form.'.elements[i].checked=true;
                   1355:                                        }
                   1356:         }
                   1357:     }
                   1358: 
                   1359:     function checksec() {
                   1360:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1361:             ele = document.forms.'.$form.'.elements[i];
                   1362:            string = document.forms.'.$form.'.chksec.value;
                   1363:            if
                   1364:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1365:               document.forms.'.$form.'.elements[i].checked=true;
                   1366:             }
                   1367:         }
                   1368:     }
                   1369: 
                   1370: 
                   1371:     function uncheckall() {
                   1372:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1373:             ele = document.forms.'.$form.'.elements[i];
                   1374:             if (ele.name == "'.$type.'") {
                   1375:             document.forms.'.$form.'.elements[i].checked=false;
                   1376:                                        }
                   1377:         }
                   1378:     }
                   1379: 
1.597     wenzelju 1380: '."\n");
1.249     albertel 1381:     return $chkallscript;
                   1382: }
                   1383: 
                   1384: sub check_buttons {
1.485     albertel 1385:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1386:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1387:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1388:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1389:     return $buttons;
                   1390: }
                   1391: 
1.44      ng       1392: #     Displays the submissions for one student or a group of students
1.34      ng       1393: sub processGroup {
1.766     raeburn  1394:     my ($request,$symb) = @_;
1.41      ng       1395:     my $ctr        = 0;
1.155     albertel 1396:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1397:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1398: 
1.396     banghart 1399:     foreach my $student (@stuchecked) {
                   1400: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1401: 	$env{'form.student'}        = $uname;
                   1402: 	$env{'form.userdom'}        = $udom;
                   1403: 	$env{'form.fullname'}       = $fullname;
1.619     www      1404: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1405: 	$ctr++;
                   1406:     }
                   1407:     return '';
1.35      ng       1408: }
1.34      ng       1409: 
1.44      ng       1410: #------------------------------------------------------------------------------------
                   1411: #
                   1412: #-------------------------- Next few routines handles grading by student, essentially
                   1413: #                           handles essay response type problem/part
                   1414: #
                   1415: #--- Javascript to handle the submission page functionality ---
                   1416: sub sub_page_js {
                   1417:     my $request = shift;
1.736     damieng  1418:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1419:     &js_escape(\$alertmsg);
1.597     wenzelju 1420:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1421:     function updateRadio(formname,id,weight) {
1.125     ng       1422: 	var gradeBox = formname["GD_BOX"+id];
                   1423: 	var radioButton = formname["RADVAL"+id];
                   1424: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1425: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1426: 	gradeBox.value = pts;
                   1427: 	var resetbox = false;
                   1428: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1429: 	    alert("$alertmsg"+pts);
1.71      ng       1430: 	    for (var i=0; i<radioButton.length; i++) {
                   1431: 		if (radioButton[i].checked) {
                   1432: 		    gradeBox.value = i;
                   1433: 		    resetbox = true;
                   1434: 		}
                   1435: 	    }
                   1436: 	    if (!resetbox) {
                   1437: 		formtextbox.value = "";
                   1438: 	    }
                   1439: 	    return;
1.44      ng       1440: 	}
1.71      ng       1441: 
                   1442: 	if (pts > weight) {
                   1443: 	    var resp = confirm("You entered a value ("+pts+
                   1444: 			       ") greater than the weight for the part. Accept?");
                   1445: 	    if (resp == false) {
1.125     ng       1446: 		gradeBox.value = oldpts;
1.71      ng       1447: 		return;
                   1448: 	    }
1.44      ng       1449: 	}
1.13      albertel 1450: 
1.71      ng       1451: 	for (var i=0; i<radioButton.length; i++) {
                   1452: 	    radioButton[i].checked=false;
                   1453: 	    if (pts == i && pts != "") {
                   1454: 		radioButton[i].checked=true;
                   1455: 	    }
                   1456: 	}
                   1457: 	updateSelect(formname,id);
1.125     ng       1458: 	formname["stores"+id].value = "0";
1.41      ng       1459:     }
1.5       albertel 1460: 
1.72      ng       1461:     function writeBox(formname,id,pts) {
1.125     ng       1462: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1463: 	if (checkSolved(formname,id) == 'update') {
                   1464: 	    gradeBox.value = pts;
                   1465: 	} else {
1.125     ng       1466: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1467: 	    gradeBox.value = oldpts;
1.125     ng       1468: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1469: 	    for (var i=0; i<radioButton.length; i++) {
                   1470: 		radioButton[i].checked=false;
1.72      ng       1471: 		if (i == oldpts) {
1.71      ng       1472: 		    radioButton[i].checked=true;
                   1473: 		}
                   1474: 	    }
1.41      ng       1475: 	}
1.125     ng       1476: 	formname["stores"+id].value = "0";
1.71      ng       1477: 	updateSelect(formname,id);
                   1478: 	return;
1.41      ng       1479:     }
1.44      ng       1480: 
1.71      ng       1481:     function clearRadBox(formname,id) {
                   1482: 	if (checkSolved(formname,id) == 'noupdate') {
                   1483: 	    updateSelect(formname,id);
                   1484: 	    return;
                   1485: 	}
1.125     ng       1486: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1487: 	for (var i=0; i<gradeSelect.length; i++) {
                   1488: 	    if (gradeSelect[i].selected) {
                   1489: 		var selectx=i;
                   1490: 	    }
                   1491: 	}
1.125     ng       1492: 	var stores = formname["stores"+id];
1.71      ng       1493: 	if (selectx == stores.value) { return };
1.125     ng       1494: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1495: 	gradeBox.value = "";
1.125     ng       1496: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1497: 	for (var i=0; i<radioButton.length; i++) {
                   1498: 	    radioButton[i].checked=false;
                   1499: 	}
                   1500: 	stores.value = selectx;
                   1501:     }
1.5       albertel 1502: 
1.71      ng       1503:     function checkSolved(formname,id) {
1.125     ng       1504: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1505: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1506: 	    if (!reply) {return "noupdate";}
1.120     ng       1507: 	    formname.overRideScore.value = 'yes';
1.41      ng       1508: 	}
1.71      ng       1509: 	return "update";
1.13      albertel 1510:     }
1.71      ng       1511: 
                   1512:     function updateSelect(formname,id) {
1.125     ng       1513: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1514: 	return;
1.41      ng       1515:     }
1.33      ng       1516: 
1.121     ng       1517: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1518:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1519: 	formname.gradeOpt.value = val;
1.71      ng       1520: 	if (val == "Save & Next") {
                   1521: 	    for (i=0;i<=total;i++) {
                   1522: 		for (j=0;j<parttot;j++) {
1.125     ng       1523: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1524: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1525: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1526: 			if (points == "") {
1.125     ng       1527: 			    var name = formname["name"+i].value;
1.129     ng       1528: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1529: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1530: 					       ", part "+partid+". Continue?");
1.71      ng       1531: 			    if (resp == false) {
1.125     ng       1532: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1533: 				return false;
                   1534: 			    }
                   1535: 			}
                   1536: 		    }
                   1537: 		}
                   1538: 	    }
                   1539: 	}
1.120     ng       1540: 	formname.submit();
                   1541:     }
                   1542: 
1.71      ng       1543: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1544:     function checkSubmitPage(formname,total) {
                   1545: 	noscore = new Array(100);
                   1546: 	var ptr = 0;
                   1547: 	for (i=1;i<total;i++) {
1.125     ng       1548: 	    var partid = formname["q_"+i].value;
1.127     ng       1549: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1550: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1551: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1552: 		if (points == "" && status != "correct_by_student") {
                   1553: 		    noscore[ptr] = i;
                   1554: 		    ptr++;
                   1555: 		}
                   1556: 	    }
                   1557: 	}
                   1558: 	if (ptr != 0) {
                   1559: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1560: 	    var prolist = "";
                   1561: 	    if (ptr == 1) {
                   1562: 		prolist = noscore[0];
                   1563: 	    } else {
                   1564: 		var i = 0;
                   1565: 		while (i < ptr-1) {
                   1566: 		    prolist += noscore[i]+", ";
                   1567: 		    i++;
                   1568: 		}
                   1569: 		prolist += "and "+noscore[i];
                   1570: 	    }
                   1571: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1572: 	    if (resp == false) {
                   1573: 		return false;
                   1574: 	    }
                   1575: 	}
1.45      ng       1576: 
1.71      ng       1577: 	formname.submit();
                   1578:     }
                   1579: SUBJAVASCRIPT
                   1580: }
1.45      ng       1581: 
1.773     raeburn  1582: #--- javascript for grading message center
                   1583: sub sub_grademessage_js {
1.71      ng       1584:     my $request = shift;
1.80      ng       1585:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1586:     &commonJSfunctions($request);
1.350     albertel 1587: 
1.629     www      1588:     my $inner_js_msg_central= (<<INNERJS);
                   1589: <script type="text/javascript">
1.350     albertel 1590:     function checkInput() {
                   1591:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1592:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1593:       var usrctr = document.msgcenter.usrctr.value;
                   1594:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1595:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1596: 
                   1597:       var msgchk = "";
                   1598:       if (document.msgcenter.subchk.checked) {
                   1599:          msgchk = "msgsub,";
                   1600:       }
                   1601:       var includemsg = 0;
                   1602:       for (var i=1; i<=nmsg; i++) {
                   1603:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1604:           var frmmsg = document.msgcenter["msg"+i];
                   1605:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1606:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1607:           showflg.value = "1";
                   1608:           var chkbox = document.msgcenter["msgn"+i];
                   1609:           if (chkbox.checked) {
                   1610:              msgchk += "savemsg"+i+",";
                   1611:              includemsg = 1;
                   1612:           }
                   1613:       }
                   1614:       if (document.msgcenter.newmsgchk.checked) {
                   1615:          msgchk += "newmsg"+usrctr;
                   1616:          includemsg = 1;
                   1617:       }
                   1618:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1619:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1620:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1621:       includemsg.value = msgchk;
                   1622: 
                   1623:       self.close()
                   1624: 
                   1625:     }
1.629     www      1626: </script>
1.350     albertel 1627: INNERJS
                   1628: 
1.773     raeburn  1629:     my $start_page_msg_central =
1.351     albertel 1630:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1631: 				       {'js_ready'  => 1,
                   1632: 					'only_body' => 1,
                   1633: 					'bgcolor'   =>'#FFFFFF',});
1.773     raeburn  1634:     my $end_page_msg_central =
1.350     albertel 1635: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1636: 
1.219     www      1637:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1638:     $docopen=~s/^document\.//;
1.773     raeburn  1639: 
1.736     damieng  1640:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1641:                 comp => 'Compose Message for: ',
                   1642:                 incl => 'Include',
1.656     raeburn  1643:                 type => 'Type',
1.652     raeburn  1644:                 subj => 'Subject',
                   1645:                 mesa => 'Message',
                   1646:                 new  => 'New',
                   1647:                 save => 'Save',
                   1648:                 canc => 'Cancel',
                   1649:              );
1.736     damieng  1650:     &html_escape(\%html_js_lt);
                   1651:     &js_escape(\%html_js_lt);
1.597     wenzelju 1652:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1653: 
1.44      ng       1654: //===================== Script to view submitted by ==================
                   1655:   function viewSubmitter(submitter) {
                   1656:     document.SCORE.refresh.value = "on";
                   1657:     document.SCORE.NCT.value = "1";
                   1658:     document.SCORE.unamedom0.value = submitter;
                   1659:     document.SCORE.submit();
                   1660:     return;
                   1661:   }
                   1662: 
                   1663: //====================== Script for composing message ==============
1.80      ng       1664:    // preload images
                   1665:    img1 = new Image();
                   1666:    img1.src = "$iconpath/mailbkgrd.gif";
                   1667:    img2 = new Image();
                   1668:    img2.src = "$iconpath/mailto.gif";
                   1669: 
1.44      ng       1670:   function msgCenter(msgform,usrctr,fullname) {
                   1671:     var Nmsg  = msgform.savemsgN.value;
                   1672:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1673:     var subject = msgform.msgsub.value;
1.127     ng       1674:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1675:     re = /msgsub/;
                   1676:     var shwsel = "";
                   1677:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1678:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1679:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1680:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1681: 	var testmsg = "savemsg"+i+",";
                   1682: 	re = new RegExp(testmsg,"g");
1.44      ng       1683: 	shwsel = "";
                   1684: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1685: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1686: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1687: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1688: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1689:     }
1.125     ng       1690:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1691:     shwsel = "";
                   1692:     re = /newmsg/;
                   1693:     if (re.test(msgchk)) { shwsel = "checked" }
                   1694:     newMsg(newmsg,shwsel);
                   1695:     msgTail(); 
                   1696:     return;
                   1697:   }
                   1698: 
1.123     ng       1699:   function checkEntities(strx) {
                   1700:     if (strx.length == 0) return strx;
                   1701:     var orgStr = ["&", "<", ">", '"']; 
                   1702:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1703:     var counter = 0;
                   1704:     while (counter < 4) {
                   1705: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1706: 	counter++;
                   1707:     }
                   1708:     return strx;
                   1709:   }
                   1710: 
                   1711:   function strReplace(strx, orgStr, newStr) {
                   1712:     return strx.split(orgStr).join(newStr);
                   1713:   }
                   1714: 
1.44      ng       1715:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1716:     var height = 70*Nmsg+250;
1.44      ng       1717:     if (height > 600) {
                   1718: 	height = 600;
                   1719:     }
1.118     ng       1720:     var xpos = (screen.width-600)/2;
                   1721:     xpos = (xpos < 0) ? '0' : xpos;
                   1722:     var ypos = (screen.height-height)/2-30;
                   1723:     ypos = (ypos < 0) ? '0' : ypos;
                   1724: 
1.668     www      1725:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1726:     pWin.focus();
                   1727:     pDoc = pWin.document;
1.219     www      1728:     pDoc.$docopen;
1.351     albertel 1729:     pDoc.write('$start_page_msg_central');
1.76      ng       1730: 
                   1731:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1732:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1733:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1734: 
1.676     golterma 1735:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1736:     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       1737: }
                   1738:     function displaySubject(msg,shwsel) {
1.76      ng       1739:     pDoc = pWin.document;
1.676     golterma 1740:     pDoc.write("<tr>");
                   1741:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1742:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1743:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1744: }
                   1745: 
1.72      ng       1746:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1747:     pDoc = pWin.document;
1.676     golterma 1748:     pDoc.write("<tr>");
                   1749:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1750:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1751:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1752: }
                   1753: 
                   1754:   function newMsg(newmsg,shwsel) {
1.76      ng       1755:     pDoc = pWin.document;
1.676     golterma 1756:     pDoc.write("<tr>");
                   1757:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1758:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1759:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1760: }
                   1761: 
                   1762:   function msgTail() {
1.76      ng       1763:     pDoc = pWin.document;
1.676     golterma 1764:     //pDoc.write("<\\/table>");
1.465     albertel 1765:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1766:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1767:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1768:     pDoc.write("<\\/form>");
1.351     albertel 1769:     pDoc.write('$end_page_msg_central');
1.128     ng       1770:     pDoc.close();
1.44      ng       1771: }
                   1772: 
1.773     raeburn  1773: SUBJAVASCRIPT
                   1774: }
                   1775: 
                   1776: #--- javascript for essay type problem --
                   1777: sub sub_page_kw_js {
                   1778:     my $request = shift;
                   1779: 
                   1780:     unless ($env{'form.compmsg'}) {
                   1781:         &commonJSfunctions($request);
                   1782:     }
                   1783: 
                   1784:     my $inner_js_highlight_central= (<<INNERJS);
                   1785: <script type="text/javascript">
                   1786:     function updateChoice(flag) {
                   1787:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1788:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1789:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1790:       opener.document.SCORE.refresh.value = "on";
                   1791:       if (opener.document.SCORE.keywords.value!=""){
                   1792:          opener.document.SCORE.submit();
                   1793:       }
                   1794:       self.close()
                   1795:     }
                   1796: </script>
                   1797: INNERJS
                   1798: 
                   1799:     my $start_page_highlight_central =
                   1800:         &Apache::loncommon::start_page('Highlight Central',
                   1801:                                        $inner_js_highlight_central,
                   1802:                                        {'js_ready'  => 1,
                   1803:                                         'only_body' => 1,
                   1804:                                         'bgcolor'   =>'#FFFFFF',});
                   1805:     my $end_page_highlight_central =
                   1806:         &Apache::loncommon::end_page({'js_ready' => 1});
                   1807: 
                   1808:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1809:     $docopen=~s/^document\.//;
                   1810: 
                   1811:     my %js_lt = &Apache::lonlocal::texthash(
                   1812:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1813:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1814:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1815:                 col1 => 'red',
                   1816:                 col2 => 'green',
                   1817:                 col3 => 'blue',
                   1818:                 siz1 => 'normal',
                   1819:                 siz2 => '+1',
                   1820:                 siz3 => '+2',
                   1821:                 sty1 => 'normal',
                   1822:                 sty2 => 'italic',
                   1823:                 sty3 => 'bold',
                   1824:              );
                   1825:     my %html_js_lt = &Apache::lonlocal::texthash(
                   1826:                 save => 'Save',
                   1827:                 canc => 'Cancel',
                   1828:                 kehi => 'Keyword Highlight Options',
                   1829:                 txtc => 'Text Color',
                   1830:                 font => 'Font Size',
                   1831:                 fnst => 'Font Style',
                   1832:              );
                   1833:     &js_escape(\%js_lt);
                   1834:     &html_escape(\%html_js_lt);
                   1835:     &js_escape(\%html_js_lt);
                   1836:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1837: 
                   1838: //===================== Show list of keywords ====================
                   1839:   function keywords(formname) {
                   1840:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1841:     if (nret==null) return;
                   1842:     formname.keywords.value = nret;
                   1843: 
                   1844:     if (formname.keywords.value != "") {
                   1845:         formname.refresh.value = "on";
                   1846:         formname.submit();
                   1847:     }
                   1848:     return;
                   1849:   }
                   1850: 
                   1851: //===================== Script to add keyword(s) ==================
                   1852:   function getSel() {
                   1853:     if (document.getSelection) txt = document.getSelection();
                   1854:     else if (document.selection) txt = document.selection.createRange().text;
                   1855:     else return;
                   1856:     if (typeof(txt) != 'string') {
                   1857:         txt = String(txt);
                   1858:     }
                   1859:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1860:     if (cleantxt=="") {
                   1861:         alert("$js_lt{'plse'}");
                   1862:         return;
                   1863:     }
                   1864:     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1865:     if (nret==null) return;
                   1866:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1867:     if (document.SCORE.keywords.value != "") {
                   1868:         document.SCORE.refresh.value = "on";
                   1869:         document.SCORE.submit();
                   1870:     }
                   1871:     return;
                   1872:   }
                   1873: 
1.44      ng       1874: //====================== Script for keyword highlight options ==============
                   1875:   function kwhighlight() {
                   1876:     var kwclr    = document.SCORE.kwclr.value;
                   1877:     var kwsize   = document.SCORE.kwsize.value;
                   1878:     var kwstyle  = document.SCORE.kwstyle.value;
                   1879:     var redsel = "";
                   1880:     var grnsel = "";
                   1881:     var blusel = "";
1.736     damieng  1882:     var txtcol1 = "$js_lt{'col1'}";
                   1883:     var txtcol2 = "$js_lt{'col2'}";
                   1884:     var txtcol3 = "$js_lt{'col3'}";
                   1885:     var txtsiz1 = "$js_lt{'siz1'}";
                   1886:     var txtsiz2 = "$js_lt{'siz2'}";
                   1887:     var txtsiz3 = "$js_lt{'siz3'}";
                   1888:     var txtsty1 = "$js_lt{'sty1'}";
                   1889:     var txtsty2 = "$js_lt{'sty2'}";
                   1890:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1891:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1892:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1893:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1894:     var sznsel = "";
                   1895:     var sz1sel = "";
                   1896:     var sz2sel = "";
1.718     bisitz   1897:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1898:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1899:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1900:     var synsel = "";
                   1901:     var syisel = "";
                   1902:     var sybsel = "";
1.718     bisitz   1903:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1904:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1905:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1906:     highlightCentral();
1.718     bisitz   1907:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1908:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1909:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1910:     highlightend();
                   1911:     return;
                   1912:   }
                   1913: 
                   1914:   function highlightCentral() {
1.76      ng       1915: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1916:     var xpos = (screen.width-400)/2;
                   1917:     xpos = (xpos < 0) ? '0' : xpos;
                   1918:     var ypos = (screen.height-330)/2-30;
                   1919:     ypos = (ypos < 0) ? '0' : ypos;
                   1920: 
1.206     albertel 1921:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1922:     hwdWin.focus();
                   1923:     var hDoc = hwdWin.document;
1.219     www      1924:     hDoc.$docopen;
1.351     albertel 1925:     hDoc.write('$start_page_highlight_central');
1.76      ng       1926:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1927:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1928: 
1.718     bisitz   1929:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1930:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1931:   }
                   1932: 
                   1933:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1934:     var hDoc = hwdWin.document;
1.718     bisitz   1935:     hDoc.write("<tr>");
1.76      ng       1936:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1937:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1938:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1939:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1940:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1941:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1942:     hDoc.write("<\\/tr>");
1.44      ng       1943:   }
                   1944: 
                   1945:   function highlightend() { 
1.76      ng       1946:     var hDoc = hwdWin.document;
1.718     bisitz   1947:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1948:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1949:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1950:     hDoc.write("<\\/form>");
1.351     albertel 1951:     hDoc.write('$end_page_highlight_central');
1.128     ng       1952:     hDoc.close();
1.44      ng       1953:   }
                   1954: 
                   1955: SUBJAVASCRIPT
                   1956: }
                   1957: 
1.349     albertel 1958: sub get_increment {
1.348     bowersj2 1959:     my $increment = $env{'form.increment'};
                   1960:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1961:         $increment != .1) {
                   1962:         $increment = 1;
                   1963:     }
                   1964:     return $increment;
                   1965: }
                   1966: 
1.585     bisitz   1967: sub gradeBox_start {
                   1968:     return (
                   1969:         &Apache::loncommon::start_data_table()
                   1970:        .&Apache::loncommon::start_data_table_header_row()
                   1971:        .'<th>'.&mt('Part').'</th>'
                   1972:        .'<th>'.&mt('Points').'</th>'
                   1973:        .'<th>&nbsp;</th>'
                   1974:        .'<th>'.&mt('Assign Grade').'</th>'
                   1975:        .'<th>'.&mt('Weight').'</th>'
                   1976:        .'<th>'.&mt('Grade Status').'</th>'
                   1977:        .&Apache::loncommon::end_data_table_header_row()
                   1978:     );
                   1979: }
                   1980: 
                   1981: sub gradeBox_end {
                   1982:     return (
                   1983:         &Apache::loncommon::end_data_table()
                   1984:     );
                   1985: }
1.71      ng       1986: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1987: sub gradeBox {
1.322     albertel 1988:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1989:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1990: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1991:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1992:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1993:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1994:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1995:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1996: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1997:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1998:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1999:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2000: 				       [$partid]);
                   2001:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2002:     if ($last_resets{$partid}) {
                   2003:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2004:     }
1.695     bisitz   2005:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2006:     my $ctr = 0;
1.348     bowersj2 2007:     my $thisweight = 0;
1.349     albertel 2008:     my $increment = &get_increment();
1.485     albertel 2009: 
                   2010:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2011:     while ($thisweight<=$wgt) {
1.532     bisitz   2012: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2013:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2014: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2015: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2016: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2017:         $thisweight += $increment;
1.71      ng       2018: 	$ctr++;
                   2019:     }
1.485     albertel 2020:     $radio.='</tr></table>';
                   2021: 
                   2022:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2023: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2024: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2025: 	$wgt.')" /></td>'."\n";
1.485     albertel 2026:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2027: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2028: 	' </td>'."\n";
                   2029:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2030: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2031:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2032: 	$line.='<option></option>'.
                   2033: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2034:     } else {
1.485     albertel 2035: 	$line.='<option selected="selected"></option>'.
                   2036: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2037:     }
1.485     albertel 2038:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2039: 
                   2040: 
                   2041:     $result .= 
1.695     bisitz   2042: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2043:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2044:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2045:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2046: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2047: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2048: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2049:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2050:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2051:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2052:         $aggtries.'" />'."\n";
1.582     raeburn  2053:     my $res_error;
                   2054:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2055:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2056:     if ($res_error) {
                   2057:         return &navmap_errormsg();
                   2058:     }
1.318     banghart 2059:     return $result;
                   2060: }
1.322     albertel 2061: 
                   2062: sub handback_box {
1.623     www      2063:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773     raeburn  2064:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2065:     return unless ($numessay);
1.323     banghart 2066:     my (@respids);
1.652     raeburn  2067:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2068:     foreach my $part_response_id (@part_response_id) {
                   2069:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2070:         if ($part eq $partid) {
1.375     albertel 2071:             push(@respids,$resp);
1.323     banghart 2072:         }
                   2073:     }
1.318     banghart 2074:     my $result;
1.323     banghart 2075:     foreach my $respid (@respids) {
1.322     albertel 2076: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2077: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2078: 	next if (!@$files);
1.654     raeburn  2079: 	my $file_counter = 0;
1.313     banghart 2080: 	foreach my $file (@$files) {
1.368     banghart 2081: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2082:                 $file_counter++;
1.368     banghart 2083:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2084:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2085:     	        $file_disp = "$name.$ext";
                   2086:     	        $file = $file_path.$file_disp;
                   2087:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2088:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2089:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2090:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2091: 	    }
1.322     albertel 2092: 	}
1.654     raeburn  2093:         if ($file_counter) {
                   2094:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2095:                        '<span class="LC_info">'.
                   2096:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2097:         }
1.313     banghart 2098:     }
1.318     banghart 2099:     return $result;    
1.71      ng       2100: }
1.44      ng       2101: 
1.58      albertel 2102: sub show_problem {
1.382     albertel 2103:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2104:     my $rendered;
1.382     albertel 2105:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2106:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2107:     if ($mode eq 'both' or $mode eq 'text') {
                   2108: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2109: 						       $env{'request.course.id'},
                   2110: 						       undef,\%form);
1.144     albertel 2111:     }
1.58      albertel 2112:     if ($removeform) {
                   2113: 	$rendered=~s|<form(.*?)>||g;
                   2114: 	$rendered=~s|</form>||g;
1.374     albertel 2115: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2116:     }
1.144     albertel 2117:     my $companswer;
                   2118:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2119: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2120: 	$companswer=
                   2121: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2122: 						    $env{'request.course.id'},
                   2123: 						    %form);
1.144     albertel 2124:     }
1.58      albertel 2125:     if ($removeform) {
                   2126: 	$companswer=~s|<form(.*?)>||g;
                   2127: 	$companswer=~s|</form>||g;
1.144     albertel 2128: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2129:     }
1.671     raeburn  2130:     my $renderheading = &mt('View of the problem');
                   2131:     my $answerheading = &mt('Correct answer');
                   2132:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2133:         my $stu_fullname = $env{'form.fullname'};
                   2134:         if ($stu_fullname eq '') {
                   2135:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2136:         }
                   2137:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2138:         if ($forwhom ne '') {
                   2139:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2140:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2141:         }
                   2142:     }
1.468     albertel 2143:     $rendered=
1.588     bisitz   2144:         '<div class="LC_Box">'
1.671     raeburn  2145:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2146:        .$rendered
                   2147:        .'</div>';
1.468     albertel 2148:     $companswer=
1.588     bisitz   2149:         '<div class="LC_Box">'
1.671     raeburn  2150:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2151:        .$companswer
                   2152:        .'</div>';
1.468     albertel 2153:     my $result;
1.144     albertel 2154:     if ($mode eq 'both') {
1.588     bisitz   2155:         $result=$rendered.$companswer;
1.144     albertel 2156:     } elsif ($mode eq 'text') {
1.588     bisitz   2157:         $result=$rendered;
1.144     albertel 2158:     } elsif ($mode eq 'answer') {
1.588     bisitz   2159:         $result=$companswer;
1.144     albertel 2160:     }
1.71      ng       2161:     return $result;
1.58      albertel 2162: }
1.397     albertel 2163: 
1.396     banghart 2164: sub files_exist {
                   2165:     my ($r, $symb) = @_;
                   2166:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2167:     foreach my $student (@students) {
                   2168:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2169:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2170: 					      $udom,$uname);
1.396     banghart 2171:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2172:         foreach my $submission (@$string) {
                   2173:             my ($partid,$respid) =
                   2174: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2175:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2176: 					   \%record);
                   2177:             return 1 if (@$files);
1.396     banghart 2178:         }
                   2179:     }
1.397     albertel 2180:     return 0;
1.396     banghart 2181: }
1.397     albertel 2182: 
1.394     banghart 2183: sub download_all_link {
                   2184:     my ($r,$symb) = @_;
1.621     www      2185:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2186:         $r->print(&mt('There are currently no submitted documents.'));
                   2187:         return;
1.621     www      2188:     }
1.395     albertel 2189:     my $all_students = 
                   2190: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2191: 
                   2192:     my $parts =
                   2193: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2194: 
1.394     banghart 2195:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2196:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2197:                              'cgi.'.$identifier.'.symb' => $symb,
                   2198:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2199:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2200: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2201:     return;
                   2202: }
                   2203: 
                   2204: sub submit_download_link {
                   2205:     my ($request,$symb) = @_;
                   2206:     if (!$symb) { return ''; }
1.750     raeburn  2207:     my $res_error;
1.773     raeburn  2208:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2209:         &response_type($symb,\$res_error);
                   2210:     if ($res_error) {
                   2211:         $request->print(&mt('An error occurred retrieving response types'));
                   2212:         return;
                   2213:     }
                   2214:     unless ($numessay) {
                   2215:         $request->print(&mt('No essayresponse items found'));
                   2216:         return;
1.750     raeburn  2217:     }
1.773     raeburn  2218:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2219:     if (@chosenparts) {
                   2220:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2221:                                           undef,undef,1));
1.750     raeburn  2222:     }
1.773     raeburn  2223:     if ($numessay) {
1.750     raeburn  2224:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2225:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2226:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2227:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2228:         if (ref($fullname) eq 'HASH') {
                   2229:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2230:             if (@students) {
                   2231:                 @{$env{'form.stuinfo'}} = @students;
1.773     raeburn  2232:                 if ($numdropbox) {
1.750     raeburn  2233:                     &download_all_link($request,$symb);
1.773     raeburn  2234:                 } else {
                   2235:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2236:                 }
1.773     raeburn  2237: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2238: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2239:             } else {
                   2240:                 $request->print(&mt('No students match the criteria you selected'));
                   2241:             }
                   2242:         } else {
                   2243:             $request->print(&mt('Could not retrieve student information'));
                   2244:         }
                   2245:     } else {
                   2246:         $request->print(&mt('No essayresponse items found'));
                   2247:     }
                   2248:     return;
1.394     banghart 2249: }
1.395     albertel 2250: 
1.432     banghart 2251: sub build_section_inputs {
                   2252:     my $section_inputs;
                   2253:     if ($env{'form.section'} eq '') {
                   2254:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2255:     } else {
                   2256:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2257:         foreach my $section (@sections) {
1.432     banghart 2258:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2259:         }
                   2260:     }
                   2261:     return $section_inputs;
                   2262: }
                   2263: 
1.44      ng       2264: # --------------------------- show submissions of a student, option to grade 
                   2265: sub submission {
1.773     raeburn  2266:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2267:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2268:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2269:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2270:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2271: 
1.324     albertel 2272:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773     raeburn  2273:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2274:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2275:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2276: 
                   2277:     if (!&canview($usec)) {
1.712     bisitz   2278:         $request->print(
                   2279:             '<span class="LC_warning">'.
1.713     bisitz   2280:             &mt('Unable to view requested student.').
1.712     bisitz   2281:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2282:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2283:             '</span>');
1.104     albertel 2284: 	return;
                   2285:     }
                   2286: 
1.773     raeburn  2287:     my $res_error;
                   2288:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2289:         &response_type($symb,\$res_error);
                   2290:     if ($res_error) {
                   2291:         $request->print(&navmap_errormsg());
                   2292:         return;
                   2293:     }
                   2294: 
1.257     albertel 2295:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2296:     unless ($is_tool) { 
                   2297:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2298:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2299:     }
1.773     raeburn  2300:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2301:         $env{'form.compmsg'} = 1;
                   2302:     }
1.257     albertel 2303:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2304:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2305: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2306: 	'/check.gif" height="16" border="0" />';
1.41      ng       2307: 
                   2308:     # header info
                   2309:     if ($counter == 0) {
1.773     raeburn  2310:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2311:         if (@chosenparts) {
                   2312:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2313:         } elsif ($divforres) {
                   2314:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2315:         } else {
                   2316:             $request->print('<br clear="all" />');
                   2317:         }
1.41      ng       2318: 	&sub_page_js($request);
1.773     raeburn  2319:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2320: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2321: 
1.44      ng       2322: 	# option to display problem, only once else it cause problems 
                   2323:         # with the form later since the problem has a form.
1.257     albertel 2324: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2325: 	    my $mode;
1.257     albertel 2326: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2327: 		$mode='both';
1.257     albertel 2328: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2329: 		$mode='text';
1.257     albertel 2330: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2331: 		$mode='answer';
                   2332: 	    }
1.329     albertel 2333: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2334: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2335: 	}
1.441     www      2336: 
1.41      ng       2337: 	my %keyhash = ();
1.773     raeburn  2338: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2339: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2340: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2341: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773     raeburn  2342: 	}
                   2343: 	# kwclr is the only variable that is guaranteed not to be blank
                   2344: 	# if this subroutine has been called once.
                   2345: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2346: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2347: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2348: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2349: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2350: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773     raeburn  2351: 	}
                   2352: 	if ($env{'form.compmsg'}) {
                   2353: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      2354: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2355: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2356: 	}
1.773     raeburn  2357: 
1.257     albertel 2358: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2359: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2360: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2361: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2362: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2363: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2364: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2365: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2366: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2367: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2368: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2369: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2370: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773     raeburn  2371: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2372: 			&build_section_inputs().
1.326     albertel 2373: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2374: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2375: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773     raeburn  2376: 	if ($env{'form.compmsg'}) {
                   2377: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2378: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2379: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2380: 	}
                   2381: 	if ($numessay) {
1.257     albertel 2382: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2383: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2384: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773     raeburn  2385: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2386: 	}
1.773     raeburn  2387: 
1.41      ng       2388: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2389: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2390: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2391: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2392: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2393: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2394: 		'" />'."\n".
                   2395: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2396: 	    $cts++;
                   2397: 	}
                   2398: 	$request->print($prnmsg);
1.32      ng       2399: 
1.773     raeburn  2400: 	if ($numessay) {
1.652     raeburn  2401: 
                   2402:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2403:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2404:                           keyw => 'Keyword Options',
1.655     raeburn  2405:                           list => 'List',
1.652     raeburn  2406:                           past => 'Paste Selection to List',
1.661     www      2407:                           high => 'Highlight Attribute',
1.773     raeburn  2408:                      );
1.88      www      2409: #
                   2410: # Print out the keyword options line
                   2411: #
1.718     bisitz   2412: 	    $request->print(
                   2413:                 '<div class="LC_columnSection">'
                   2414:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2415:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2416:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2417:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2418:  class="page">'.$lt{'past'}.'</a>',
                   2419:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2420:                     {legend => $lt{'keyw'}})
                   2421:                .'</fieldset></div>'
                   2422:             );
                   2423: 
1.88      www      2424: #
                   2425: # Load the other essays for similarity check
                   2426: #
1.753     raeburn  2427:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2428:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2429:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2430:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2431:                 if ($cdom ne '' && $cnum ne '') {
                   2432:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2433:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2434:                         my $apath = $1.'_'.$id;
                   2435:                         $apath=~s/\W/\_/gs;
                   2436:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2437:                     }
                   2438:                 }
                   2439:             } else {
                   2440: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2441: 	        $apath=&escape($apath);
                   2442: 	        $apath=~s/\W/\_/gs;
                   2443:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2444:             }
1.41      ng       2445:         }
                   2446:     }
1.44      ng       2447: 
1.441     www      2448: # This is where output for one specific student would start
1.592     bisitz   2449:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2450:     $request->print(
                   2451:         "\n\n"
                   2452:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2453:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2454:        ."\n"
                   2455:     );
1.441     www      2456: 
1.592     bisitz   2457:     # Show additional functions if allowed
                   2458:     if ($perm{'vgr'}) {
                   2459:         $request->print(
                   2460:             &Apache::loncommon::track_student_link(
1.708     bisitz   2461:                 'View recent activity',
1.592     bisitz   2462:                 $uname,$udom,'check')
                   2463:            .' '
                   2464:         );
                   2465:     }
                   2466:     if ($perm{'opa'}) {
                   2467:         $request->print(
                   2468:             &Apache::loncommon::pprmlink(
                   2469:                 &mt('Set/Change parameters'),
                   2470:                 $uname,$udom,$symb,'check'));
                   2471:     }
                   2472: 
                   2473:     # Show Problem
1.257     albertel 2474:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2475: 	my $mode;
1.257     albertel 2476: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2477: 	    $mode='both';
1.257     albertel 2478: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2479: 	    $mode='text';
1.257     albertel 2480: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2481: 	    $mode='answer';
                   2482: 	}
1.329     albertel 2483: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2484: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2485:     }
1.144     albertel 2486: 
1.257     albertel 2487:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2488: 
1.44      ng       2489:     # Display student info
1.41      ng       2490:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2491: 
1.745     raeburn  2492:     my $boxtitle = &mt('Submissions');
                   2493:     if ($is_tool) {
                   2494:         $boxtitle = &mt('Transactions')
                   2495:     }
1.590     bisitz   2496:     my $result='<div class="LC_Box">'
1.745     raeburn  2497:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2498:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2499:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773     raeburn  2500:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2501:         $result.='<p class="LC_info">'
                   2502:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2503:                 ."</p>\n";
1.469     albertel 2504:     }
                   2505: 
1.773     raeburn  2506:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2507:     my $fullname;
                   2508:     my $col_fullnames = [];
1.773     raeburn  2509:     if ($numessay) {
1.464     albertel 2510: 	(my $sub_result,$fullname,$col_fullnames)=
                   2511: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2512: 				 $counter);
                   2513: 	$result.=$sub_result;
1.41      ng       2514:     }
1.44      ng       2515:     $request->print($result."\n");
1.773     raeburn  2516: 
1.44      ng       2517:     # print student answer/submission
1.773     raeburn  2518:     # Options are (1) Last submission only
                   2519:     #             (2) Last submission (with detailed information for that submission)
                   2520:     #             (3) All transactions (by date)
                   2521:     #             (4) The whole record (with detailed information for all transactions)
                   2522: 
1.745     raeburn  2523:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.773     raeburn  2524: 
1.702     kruse    2525:     my $lastsubonly;
1.468     albertel 2526: 
1.702     kruse    2527:     if ($$timestamp eq '') {
                   2528:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2529:     } elsif ($is_tool) {
                   2530:         $lastsubonly =
                   2531:             '<div class="LC_grade_submissions_body">'
                   2532:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2533:     } else {
                   2534:         $lastsubonly =
                   2535:             '<div class="LC_grade_submissions_body">'
                   2536:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2537: 
                   2538: 	my %seenparts;
                   2539: 	my @part_response_id = &flatten_responseType($responseType);
                   2540: 	foreach my $part (@part_response_id) {
                   2541: 	    my ($partid,$respid) = @{ $part };
                   2542: 	    my $display_part=&get_display_part($partid,$symb);
                   2543: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2544: 		if (exists($seenparts{$partid})) { next; }
                   2545: 		$seenparts{$partid}=1;
                   2546:                 $request->print(
                   2547:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2548:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2549:                                '<a href="javascript:viewSubmitter(\''.
                   2550:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2551:                                '\');" target="_self">'.
                   2552:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2553:                     '<br />');
                   2554: 		next;
1.773     raeburn  2555: 	    }
1.702     kruse    2556: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2557: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2558:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2559:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2560:                     ' <span class="LC_internal_info">'.
                   2561:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2562:                     '</span>&nbsp; &nbsp;'.
                   2563: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2564: 		next;
                   2565: 	    }
                   2566: 	    foreach my $submission (@$string) {
                   2567: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2568: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2569: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2570: 		# Similarity check
                   2571:                 my $similar='';
                   2572:                 my ($type,$trial,$rndseed);
                   2573:                 if ($hide eq 'rand') {
                   2574:                     $type = 'randomizetry';
                   2575:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2576:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2577:                 }
                   2578: 	        if ($env{'form.checkPlag'}) {
1.774   ! raeburn  2579: 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
        !          2580: 		    &most_similar($uname,$udom,$symb,$subval);
1.702     kruse    2581: 		    if ($osim) {
                   2582: 			$osim=int($osim*100.0);
                   2583:                         if ($hide eq 'anon') {
                   2584:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2585:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2586:                         } else {
1.753     raeburn  2587: 			    $similar='<hr />';
                   2588:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2589:                                 $similar .= '<h3><span class="LC_warning">'.
                   2590:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2591:                                                 $osim,
                   2592:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2593:                                             '</span></h3>';
                   2594:                             } else {
                   2595:                                 my %old_course_desc;
                   2596:                                 if ($ocrsid ne '') {
                   2597:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2598:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2599:                                     } else {
                   2600:                                         my $args;
                   2601:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2602:                                             $args = {'one_time' => 1};
                   2603:                                         }
                   2604:                                         %old_course_desc =
                   2605:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2606:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2607:                                     }
                   2608:                                     $similar .=
                   2609:                                         '<h3><span class="LC_warning">'.
                   2610:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2611:                                             $osim,
                   2612:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2613:                                             $old_course_desc{'description'},
                   2614:                                             $old_course_desc{'num'},
                   2615:                                             $old_course_desc{'domain'}).
                   2616:                                         '</span></h3>';
                   2617:                                 } else {
                   2618:                                     $similar .=
                   2619:                                         '<h3><span class="LC_warning">'.
                   2620:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2621:                                             $osim,
                   2622:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2623:                                         '</span></h3>';
                   2624:                                 }
                   2625:                             }
                   2626:                             $similar .= '<blockquote><i>'.
                   2627:                                         &keywords_highlight($oessay).
                   2628:                                         '</i></blockquote><hr />';
1.702     kruse    2629:                         }
                   2630: 	            }
                   2631: 		}
                   2632: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2633:                                      undef,$type,$trial,$rndseed);
1.773     raeburn  2634:                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2635:                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2636:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
1.702     kruse    2637: 		    my $display_part=&get_display_part($partid,$symb);
                   2638:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2639:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2640:                         ' <span class="LC_internal_info">'.
                   2641:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2642:                         '</span>&nbsp; &nbsp;';
                   2643: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2644: 		    if (@$files) {
                   2645:                         if ($hide eq 'anon') {
                   2646:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2647:                         } else {
                   2648:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2649:                                         .'<br /><span class="LC_warning">';
                   2650:                             if(@$files == 1) {
                   2651:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2652:                             } else {
1.702     kruse    2653:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2654:                             }
1.774   ! raeburn  2655:                             $lastsubonly .= '</span>';
1.702     kruse    2656:                             foreach my $file (@$files) {
                   2657:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2658:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2659:                             }
                   2660:                         }
1.702     kruse    2661: 			$lastsubonly.='<br />';
                   2662:                     }
                   2663:                     if ($hide eq 'anon') {
                   2664:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2665:                     } else {
1.774   ! raeburn  2666:                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
1.724     raeburn  2667:                         if ($draft) {
                   2668:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2669:                         }
                   2670:                         $subval =
1.702     kruse    2671: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2672: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2673:                         if ($responsetype eq 'essay') {
                   2674:                             $subval =~ s{\n}{<br />}g;
                   2675:                         }
                   2676:                         $lastsubonly.=$subval."\n";
1.702     kruse    2677:                     }
1.774   ! raeburn  2678:                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.702     kruse    2679: 		    $lastsubonly.='</div>';
1.41      ng       2680: 		}
1.702     kruse    2681:             }
1.151     albertel 2682: 	}
1.702     kruse    2683: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2684:     }
                   2685:     $request->print($lastsubonly);
                   2686:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2687:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2688: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.773     raeburn  2689:     }
1.702     kruse    2690:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2691:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2692:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2693: 								 $env{'request.course.id'},
1.44      ng       2694: 								 $last,'.submission',
1.726     raeburn  2695: 								 'Apache::grades::keywords_highlight',
                   2696:                                                                  $usec,$identifier));
1.41      ng       2697:     }
1.121     ng       2698:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2699: 	.$udom.'" />'."\n");
1.44      ng       2700:     # return if view submission with no grading option
1.618     www      2701:     if (!&canmodify($usec)) {
1.633     www      2702: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2703: 	return;
1.180     albertel 2704:     } else {
1.468     albertel 2705: 	$request->print('</div>'."\n");
1.41      ng       2706:     }
1.33      ng       2707: 
1.773     raeburn  2708:     # grading message center
                   2709: 
                   2710:     if ($env{'form.compmsg'}) {
                   2711:         my $result='<div class="LC_Box">'.
                   2712:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2713:                    '<div class="LC_grade_message_center_body">';
                   2714:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2715:         my $msgfor = $givenn.' '.$lastname;
                   2716:         if (scalar(@$col_fullnames) > 0) {
                   2717:             my $lastone = pop(@$col_fullnames);
                   2718:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2719:         }
                   2720:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2721:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2722:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2723:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2724:                  ',\''.$msgfor.'\');" target="_self">'.
                   2725:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2726:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2727:                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2728:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2729:                  '<br />&nbsp;('.
                   2730:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2731:                  '</div></div>';
                   2732:         $request->print($result);
1.118     ng       2733:     }
1.41      ng       2734: 
                   2735:     my %seen = ();
                   2736:     my @partlist;
1.129     ng       2737:     my @gradePartRespid;
1.745     raeburn  2738:     my @part_response_id;
                   2739:     if ($is_tool) {
                   2740:         @part_response_id = ([0,'']);
                   2741:     } else {
                   2742:         @part_response_id = &flatten_responseType($responseType);
                   2743:     }
1.585     bisitz   2744:     $request->print(
1.588     bisitz   2745:         '<div class="LC_Box">'
                   2746:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2747:     );
1.592     bisitz   2748:     $request->print(&gradeBox_start());
1.375     albertel 2749:     foreach my $part_response_id (@part_response_id) {
                   2750:     	my ($partid,$respid) = @{ $part_response_id };
                   2751: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2752: 	next if ($seen{$partid} > 0);
1.41      ng       2753: 	$seen{$partid}++;
1.524     raeburn  2754: 	push(@partlist,$partid);
                   2755: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2756: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2757:     }
1.585     bisitz   2758:     $request->print(&gradeBox_end()); # </div>
                   2759:     $request->print('</div>');
1.468     albertel 2760: 
                   2761:     $request->print('<div class="LC_grade_info_links">');
                   2762:     $request->print('</div>');
                   2763: 
1.45      ng       2764:     $result='<input type="hidden" name="partlist'.$counter.
                   2765: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2766:     $result.='<input type="hidden" name="gradePartRespid'.
                   2767: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2768:     my $ctr = 0;
                   2769:     while ($ctr < scalar(@partlist)) {
                   2770: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2771: 	    $partlist[$ctr].'" />'."\n";
                   2772: 	$ctr++;
                   2773:     }
1.468     albertel 2774:     $request->print($result.''."\n");
1.41      ng       2775: 
1.441     www      2776: # Done with printing info for one student
                   2777: 
1.468     albertel 2778:     $request->print('</div>');#LC_grade_show_user
1.441     www      2779: 
                   2780: 
1.41      ng       2781:     # print end of form
                   2782:     if ($counter == $total) {
1.592     bisitz   2783:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2784: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2785: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2786: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2787: 	my $ntstu ='<select name="NTSTU">'.
                   2788: 	    '<option>1</option><option>2</option>'.
                   2789: 	    '<option>3</option><option>5</option>'.
                   2790: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2791: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2792: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2793:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2794: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2795: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2796: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2797: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2798:         $endform.='<span class="LC_warning">'.
                   2799:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2800:                   '</span>'."\n" ;
1.349     albertel 2801:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2802:             "' name='increment' />";
1.485     albertel 2803: 	$endform.='</td></tr></table></form>';
1.41      ng       2804: 	$request->print($endform);
                   2805:     }
                   2806:     return '';
1.38      ng       2807: }
                   2808: 
1.464     albertel 2809: sub check_collaborators {
                   2810:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2811:     my ($result,@col_fullnames);
                   2812:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2813:     foreach my $part (keys(%$handgrade)) {
                   2814: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2815: 					'.maxcollaborators',
                   2816: 					$symb,$udom,$uname);
                   2817: 	next if ($ncol <= 0);
                   2818: 	$part =~ s/\_/\./g;
                   2819: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2820: 	my (@good_collaborators, @bad_collaborators);
                   2821: 	foreach my $possible_collaborator
1.630     www      2822: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2823: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2824: 	    next if ($possible_collaborator eq '');
1.631     www      2825: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2826: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2827: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2828: 	    # Doing this grep allows 'fuzzy' specification
                   2829: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2830: 			       keys(%$classlist));
                   2831: 	    if (! scalar(@matches)) {
                   2832: 		push(@bad_collaborators, $possible_collaborator);
                   2833: 	    } else {
                   2834: 		push(@good_collaborators, @matches);
                   2835: 	    }
                   2836: 	}
                   2837: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2838: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2839: 	    foreach my $name (@good_collaborators) {
                   2840: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2841: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2842: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2843: 	    }
1.630     www      2844: 	    $result.='</ol><br />'."\n";
1.466     albertel 2845: 	    my ($part)=split(/\./,$part);
1.464     albertel 2846: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2847: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2848: 		"\n";
                   2849: 	}
                   2850: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2851: 	    $result.='<div class="LC_warning">';
1.464     albertel 2852: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2853: 	    $result .= '</div>';
                   2854: 	}         
                   2855: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2856: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2857: 	    $result .= &mt('This student has submitted too many '.
                   2858: 		'collaborators.  Maximum is [_1].',$ncol);
                   2859: 	    $result .= '</div>';
                   2860: 	}
                   2861:     }
                   2862:     return ($result,$fullname,\@col_fullnames);
                   2863: }
                   2864: 
1.44      ng       2865: #--- Retrieve the last submission for all the parts
1.38      ng       2866: sub get_last_submission {
1.745     raeburn  2867:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2868:     my (@string,$timestamp,%lasthidden);
1.119     ng       2869:     if ($$returnhash{'version'}) {
1.46      ng       2870: 	my %lasthash=();
                   2871: 	my ($version);
1.119     ng       2872: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2873: 	    foreach my $key (sort(split(/\:/,
                   2874: 					$$returnhash{$version.':keys'}))) {
                   2875: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2876: 		$timestamp = 
1.545     raeburn  2877: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2878: 	    }
                   2879: 	}
1.640     raeburn  2880:         my (%typeparts,%randombytry);
1.596     raeburn  2881:         my $showsurv = 
                   2882:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2883:         foreach my $key (sort(keys(%lasthash))) {
                   2884:             if ($key =~ /\.type$/) {
                   2885:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2886:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2887:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2888:                     my ($ign,@parts) = split(/\./,$key);
                   2889:                     pop(@parts);
1.641     raeburn  2890:                     my $id = join('.',@parts);
1.640     raeburn  2891:                     if ($lasthash{$key} eq 'randomizetry') {
                   2892:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2893:                     } else {
                   2894:                         unless ($showsurv) {
                   2895:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2896:                         }
1.596     raeburn  2897:                     }
                   2898:                     delete($lasthash{$key});
                   2899:                 }
                   2900:             }
                   2901:         }
                   2902:         my @hidden = keys(%typeparts);
1.640     raeburn  2903:         my @randomize = keys(%randombytry);
1.397     albertel 2904: 	foreach my $key (keys(%lasthash)) {
                   2905: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2906:             my $hide;
                   2907:             if (@hidden) {
                   2908:                 foreach my $id (@hidden) {
                   2909:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2910:                         $hide = 'anon';
1.596     raeburn  2911:                         last;
                   2912:                     }
                   2913:                 }
                   2914:             }
1.640     raeburn  2915:             unless ($hide) {
                   2916:                 if (@randomize) {
1.732     raeburn  2917:                     foreach my $id (@randomize) {
1.640     raeburn  2918:                         if ($key =~ /^\Q$id\E/) {
                   2919:                             $hide = 'rand';
                   2920:                             last;
                   2921:                         }
                   2922:                     }
                   2923:                 }
                   2924:             }
1.397     albertel 2925: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2926: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2927:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2928:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2929:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2930: 	}
                   2931:     }
1.397     albertel 2932:     if (!@string) {
1.745     raeburn  2933:         my $msg;
                   2934:         if ($is_tool) {
1.747     raeburn  2935:             $msg = &mt('No grade passed back.');
1.745     raeburn  2936:         } else {
                   2937:             $msg = &mt('Nothing submitted - no attempts.');
                   2938:         }
1.397     albertel 2939: 	$string[0] =
1.745     raeburn  2940: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2941:     }
                   2942:     return (\@string,\$timestamp);
1.38      ng       2943: }
1.35      ng       2944: 
1.44      ng       2945: #--- High light keywords, with style choosen by user.
1.38      ng       2946: sub keywords_highlight {
1.44      ng       2947:     my $string    = shift;
1.257     albertel 2948:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2949:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2950:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2951:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2952:     foreach my $keyword (@keylist) {
                   2953: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2954:     }
                   2955:     return $string;
1.38      ng       2956: }
1.36      ng       2957: 
1.671     raeburn  2958: # For Tasks provide a mechanism to display previous version for one specific student
                   2959: 
                   2960: sub show_previous_task_version {
                   2961:     my ($request,$symb) = @_;
                   2962:     if ($symb eq '') {
1.717     bisitz   2963:         $request->print(
                   2964:             '<span class="LC_error">'.
                   2965:             &mt('Unable to handle ambiguous references.').
                   2966:             '</span>');
1.671     raeburn  2967:         return '';
                   2968:     }
                   2969:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2970:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2971:     if (!&canview($usec)) {
1.712     bisitz   2972:         $request->print(
                   2973:             '<span class="LC_warning">'.
1.713     bisitz   2974:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2975:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2976:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2977:             '</span>');
1.671     raeburn  2978:         return;
                   2979:     }
                   2980:     my $mode = 'both';
                   2981:     my $isTask = ($symb =~/\.task$/);
                   2982:     if ($isTask) {
                   2983:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2984:             if ($env{'form.fullname'} eq '') {
                   2985:                 $env{'form.fullname'} =
                   2986:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2987:             }
                   2988:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2989:             $request->print("\n\n".
                   2990:                             '<div class="LC_grade_show_user">'.
                   2991:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2992:                             '</h2>'."\n");
                   2993:             &Apache::lonxml::clear_problem_counter();
                   2994:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2995:                             {'previousversion' => $env{'form.previousversion'} }));
                   2996:             $request->print("\n</div>");
                   2997:         }
                   2998:     }
                   2999:     return;
                   3000: }
                   3001: 
                   3002: sub choose_task_version_form {
                   3003:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3004:     my $isTask = ($symb =~/\.task$/);
                   3005:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3006:     if ($isTask) {
                   3007:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3008:                                               $udom,$uname);
                   3009:         if (($record{'resource.0.version'} eq '') ||
                   3010:             ($record{'resource.0.version'} < 2)) {
                   3011:             return ($record{'resource.0.version'},
                   3012:                     $record{'resource.0.version'},$result,$js);
                   3013:         } else {
                   3014:             $current = $record{'resource.0.version'};
                   3015:         }
                   3016:         if ($env{'form.previousversion'}) {
                   3017:             $displayed = $env{'form.previousversion'};
                   3018:             $rowtitle = &mt('Choose another version:')
                   3019:         } else {
                   3020:             $displayed = $current;
                   3021:             $rowtitle = &mt('Show earlier version:');
                   3022:         }
                   3023:         $result = '<div class="LC_left_float">';
                   3024:         my $list;
                   3025:         my $numversions = 0;
                   3026:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3027:             if ($i == $current) {
                   3028:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3029:                     next;
                   3030:                 } else {
                   3031:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3032:                     $numversions ++;
                   3033:                 }
                   3034:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3035:                 unless ($i == $env{'form.previousversion'}) {
                   3036:                     $numversions ++;
                   3037:                 }
                   3038:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3039:             }
                   3040:         }
                   3041:         if ($numversions) {
                   3042:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3043:             $result .=
                   3044:                 '<form name="getprev" method="post" action=""'.
                   3045:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3046:                 &Apache::loncommon::start_data_table().
                   3047:                 &Apache::loncommon::start_data_table_row().
                   3048:                 '<th align="left">'.$rowtitle.'</th>'.
                   3049:                 '<td><select name="version">'.
                   3050:                 '<option>'.&mt('Select').'</option>'.
                   3051:                 $list.
                   3052:                 '</select></td>'.
                   3053:                 &Apache::loncommon::end_data_table_row();
                   3054:             unless ($nomenu) {
                   3055:                 $result .= &Apache::loncommon::start_data_table_row().
                   3056:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3057:                 '<td><span class="LC_nobreak">'.
                   3058:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3059:                 &mt('Yes').'</label>'.
                   3060:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3061:                 '</span></td>'.
                   3062:                 &Apache::loncommon::end_data_table_row();
                   3063:             }
                   3064:             $result .=
                   3065:                 &Apache::loncommon::start_data_table_row().
                   3066:                 '<th align="left">&nbsp;</th>'.
                   3067:                 '<td>'.
                   3068:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3069:                 '</td>'.
                   3070:                 &Apache::loncommon::end_data_table_row().
                   3071:                 &Apache::loncommon::end_data_table().
                   3072:                 '</form>';
                   3073:             $js = &previous_display_javascript($nomenu,$current);
                   3074:         } elsif ($displayed && $nomenu) {
                   3075:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3076:         } else {
                   3077:             $result .= &mt('No previous versions to show for this student');
                   3078:         }
                   3079:         $result .= '</div>';
                   3080:     }
                   3081:     return ($current,$displayed,$result,$js);
                   3082: }
                   3083: 
                   3084: sub previous_display_javascript {
                   3085:     my ($nomenu,$current) = @_;
                   3086:     my $js = <<"JSONE";
                   3087: <script type="text/javascript">
                   3088: // <![CDATA[
                   3089: function previousVersion(uname,udom,symb) {
                   3090:     var current = '$current';
                   3091:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3092:     var prevstr = new RegExp("^\\\\d+\$");
                   3093:     if (!prevstr.test(version)) {
                   3094:         return false;
                   3095:     }
                   3096:     var url = '';
                   3097:     if (version == current) {
                   3098:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3099:     } else {
                   3100:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3101:     }
                   3102: JSONE
                   3103:     if ($nomenu) {
                   3104:         $js .= <<"JSTWO";
                   3105:     document.location.href = url;
                   3106: JSTWO
                   3107:     } else {
                   3108:         $js .= <<"JSTHREE";
                   3109:     var newwin = 0;
                   3110:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3111:         if (document.getprev.prevwin[i].checked == true) {
                   3112:             newwin = document.getprev.prevwin[i].value;
                   3113:         }
                   3114:     }
                   3115:     if (newwin == 1) {
                   3116:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3117:         url = url+'&inhibitmenu=yes';
                   3118:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3119:             previousWin = window.open(url,'',options,1);
                   3120:         } else {
                   3121:             previousWin.location.href = url;
                   3122:         }
                   3123:         previousWin.focus();
                   3124:         return false;
                   3125:     } else {
                   3126:         document.location.href = url;
                   3127:         return false;
                   3128:     }
                   3129: JSTHREE
                   3130:     }
                   3131:     $js .= <<"ENDJS";
                   3132:     return false;
                   3133: }
                   3134: // ]]>
                   3135: </script>
                   3136: ENDJS
                   3137: 
                   3138: }
                   3139: 
1.44      ng       3140: #--- Called from submission routine
1.38      ng       3141: sub processHandGrade {
1.608     www      3142:     my ($request,$symb) = @_;
1.324     albertel 3143:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3144:     my $button = $env{'form.gradeOpt'};
                   3145:     my $ngrade = $env{'form.NCT'};
                   3146:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3147:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3148:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3149: 
1.44      ng       3150:     if ($button eq 'Save & Next') {
                   3151: 	my $ctr = 0;
                   3152: 	while ($ctr < $ngrade) {
1.257     albertel 3153: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3154: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3155:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3156: 	    if ($errorflag eq 'no_score') {
                   3157: 		$ctr++;
                   3158: 		next;
                   3159: 	    }
1.104     albertel 3160: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3161: 		$request->print(
                   3162:                     '<span class="LC_error">'
                   3163:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3164:                    .'</span>');
1.104     albertel 3165: 		$ctr++;
                   3166: 		next;
                   3167: 	    }
1.726     raeburn  3168:             if ($numhidden) {
                   3169:                 $request->print(
                   3170:                     '<span class="LC_info">'
                   3171:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3172:                    .'</span><br />');
                   3173:             }
1.257     albertel 3174: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3175: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3176: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3177:             my ($feedurl,$showsymb) =
                   3178: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3179: 	    my $messagetail;
1.62      albertel 3180: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3181: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3182: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3183: 		$subject.=' ['.$restitle.']';
1.44      ng       3184: 		my (@msgnum) = split(/,/,$includemsg);
                   3185: 		foreach (@msgnum) {
1.257     albertel 3186: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3187: 		}
1.80      ng       3188: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3189: 		if ($env{'form.withgrades'.$ctr}) {
                   3190: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3191: 		    $messagetail = " for <a href=\"".
1.605     www      3192: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3193: 		}
                   3194: 		$msgstatus = 
                   3195:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3196: 						     $message.$messagetail,
1.418     albertel 3197:                                                      undef,$feedurl,undef,
1.386     raeburn  3198:                                                      undef,undef,$showsymb,
                   3199:                                                      $restitle);
1.574     bisitz   3200: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3201: 				$msgstatus.'<br />');
1.44      ng       3202: 	    }
1.257     albertel 3203: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3204: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3205: 		foreach my $collabstr (@collabstrs) {
                   3206: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3207: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3208: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3209: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3210: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3211: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3212: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3213: 			    next;
1.418     albertel 3214: 			} elsif ($message ne '') {
                   3215: 			    my ($baseurl,$showsymb) = 
                   3216: 				&get_feedurl_and_symb($symb,$collaborator,
                   3217: 						      $udom);
                   3218: 			    if ($env{'form.withgrades'.$ctr}) {
                   3219: 				$messagetail = " for <a href=\"".
1.605     www      3220:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3221: 			    }
1.418     albertel 3222: 			    $msgstatus = 
                   3223: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3224: 			}
1.44      ng       3225: 		    }
                   3226: 		}
                   3227: 	    }
                   3228: 	    $ctr++;
                   3229: 	}
                   3230:     }
                   3231: 
1.773     raeburn  3232:     my $res_error;
                   3233:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3234:     if ($res_error) {
                   3235:         $request->print(&navmap_errormsg());
                   3236:         return;
                   3237:     }
                   3238: 
                   3239:     my %keyhash = ();
                   3240:     if ($numessay) {
1.119     ng       3241: 	# Keywords sorted in alphabatical order
1.257     albertel 3242: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3243: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3244: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3245: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3246: 	$env{'form.keywords'} = join(' ',@keywords);
                   3247: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3248: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3249: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3250: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3251: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773     raeburn  3252:     }
1.119     ng       3253: 
1.773     raeburn  3254:     if ($env{'form.compmsg'}) {
1.119     ng       3255: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3256: 	# New messages are saved in env for the next student.
1.119     ng       3257: 	# All messages are saved in nohist_handgrade.db
                   3258: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3259: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3260: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3261: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3262: 		$idx++;
                   3263: 	    }
                   3264: 	    $ctr++;
1.41      ng       3265: 	}
1.119     ng       3266: 	$ctr = 0;
                   3267: 	while ($ctr < $ngrade) {
1.257     albertel 3268: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773     raeburn  3269: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3270: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3271: 	        $idx++;
1.119     ng       3272: 	    }
                   3273: 	    $ctr++;
1.41      ng       3274: 	}
1.257     albertel 3275: 	$env{'form.savemsgN'} = --$idx;
                   3276: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3277:     }
1.773     raeburn  3278:     if (($numessay) || ($env{'form.compmsg'})) {
                   3279:         my $putresult = &Apache::lonnet::put
                   3280:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
                   3281:     }
                   3282: 
1.44      ng       3283:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3284:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3285:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3286: 	my ($ctr,$total) = (0,0);
                   3287: 	while ($ctr < $ngrade) {
1.257     albertel 3288: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3289: 	    $ctr++;
                   3290: 	}
1.257     albertel 3291: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3292: 	$ctr = 0;
                   3293: 	while ($ctr < $total) {
1.257     albertel 3294: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3295: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3296: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3297: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3298: 	    $ctr++;
                   3299: 	}
                   3300: 	return '';
                   3301:     }
1.36      ng       3302: 
1.44      ng       3303:     # Get the next/previous one or group of students
1.257     albertel 3304:     my $firststu = $env{'form.unamedom0'};
                   3305:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3306:     my $ctr = 2;
1.41      ng       3307:     while ($laststu eq '') {
1.257     albertel 3308: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3309: 	$ctr++;
                   3310: 	$laststu = $firststu if ($ctr > $ngrade);
                   3311:     }
1.44      ng       3312: 
1.41      ng       3313:     my (@parsedlist,@nextlist);
                   3314:     my ($nextflg) = 0;
1.524     raeburn  3315:     foreach my $item (sort 
1.294     albertel 3316: 	     {
                   3317: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3318: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3319: 		 }
                   3320: 		 return $a cmp $b;
                   3321: 	     } (keys(%$fullname))) {
1.41      ng       3322: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3323: 	    push(@parsedlist,$item);
1.41      ng       3324: 	}
1.524     raeburn  3325: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3326: 	if ($button eq 'Previous') {
1.524     raeburn  3327: 	    last if ($item eq $firststu);
                   3328: 	    push(@parsedlist,$item);
1.41      ng       3329: 	}
                   3330:     }
                   3331:     $ctr = 0;
                   3332:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3333:     foreach my $student (@parsedlist) {
1.257     albertel 3334: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3335: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3336: 	
                   3337: 	if ($submitonly eq 'queued') {
                   3338: 	    my %queue_status = 
                   3339: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3340: 							$udom,$uname);
                   3341: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3342: 	}
                   3343: 
1.156     albertel 3344: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3345: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3346: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3347: 	    my $submitted = 0;
1.248     albertel 3348: 	    my $ungraded = 0;
                   3349: 	    my $incorrect = 0;
1.524     raeburn  3350: 	    foreach my $item (keys(%status)) {
                   3351: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3352: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3353: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3354: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3355: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3356: 		    $submitted = 0;
                   3357: 		}
1.41      ng       3358: 	    }
1.156     albertel 3359: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3360: 				     $submitonly eq 'incorrect' ||
                   3361: 				     $submitonly eq 'graded'));
1.248     albertel 3362: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3363: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3364: 	}
1.524     raeburn  3365: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3366: 	last if ($ctr == $ntstu);
1.41      ng       3367: 	$ctr++;
                   3368:     }
1.36      ng       3369: 
1.41      ng       3370:     $ctr = 0;
                   3371:     my $total = scalar(@nextlist)-1;
1.39      ng       3372: 
1.524     raeburn  3373:     foreach (sort(@nextlist)) {
1.41      ng       3374: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3375: 	$env{'form.student'}  = $uname;
                   3376: 	$env{'form.userdom'}  = $udom;
                   3377: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3378: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3379: 	$ctr++;
                   3380:     }
                   3381:     if ($total < 0) {
1.653     raeburn  3382: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3383: 	$request->print($the_end);
                   3384:     }
                   3385:     return '';
1.38      ng       3386: }
1.36      ng       3387: 
1.44      ng       3388: #---- Save the score and award for each student, if changed
1.38      ng       3389: sub saveHandGrade {
1.324     albertel 3390:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3391:     my @version_parts;
1.104     albertel 3392:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3393: 					   $env{'request.course.id'});
1.104     albertel 3394:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3395:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3396:     my @parts_graded;
1.77      ng       3397:     my %newrecord  = ();
1.726     raeburn  3398:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3399:     my %aggregate = ();
                   3400:     my $aggregateflag = 0;
1.726     raeburn  3401:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3402:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3403:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3404:         $totchg += $numchgs;
                   3405:     }
1.301     albertel 3406:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3407:     foreach my $new_part (@parts) {
1.337     banghart 3408: 	#collaborator ($submi may vary for different parts
1.259     banghart 3409: 	if ($submitter && $new_part ne $part) { next; }
                   3410: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3411: 	if ($dropMenu eq 'excused') {
1.259     banghart 3412: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3413: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3414: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3415: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3416: 		}
1.364     banghart 3417: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3418: 	    }
1.125     ng       3419: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3420: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3421: 	    foreach my $key (keys(%record)) {
1.259     banghart 3422: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3423: 	    }
1.259     banghart 3424: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3425: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3426:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3427: 
                   3428:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3429: 					       [$new_part]);
                   3430:             my $aggtries =$totaltries;
1.269     raeburn  3431:             if ($last_resets{$new_part}) {
1.270     albertel 3432:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3433: 					   $new_part);
1.269     raeburn  3434:             }
1.270     albertel 3435: 
                   3436:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3437:             if ($aggtries > 0) {
1.327     albertel 3438:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3439:                 $aggregateflag = 1;
                   3440:             }
1.125     ng       3441: 	} elsif ($dropMenu eq '') {
1.259     banghart 3442: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3443: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3444: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3445: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3446: 		next;
                   3447: 	    }
1.259     banghart 3448: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3449: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3450: 	    my $partial= $pts/$wgt;
1.259     banghart 3451: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3452: 		#do not update score for part if not changed.
1.346     banghart 3453:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3454: 		next;
1.251     banghart 3455: 	    } else {
1.524     raeburn  3456: 	        push(@parts_graded,$new_part);
1.153     albertel 3457: 	    }
1.259     banghart 3458: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3459: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3460: 	    }
1.259     banghart 3461: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3462: 	    if ($partial == 0) {
1.153     albertel 3463: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3464: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3465: 		}
1.41      ng       3466: 	    } else {
1.153     albertel 3467: 		if ($record{$reckey} ne 'correct_by_override') {
                   3468: 		    $newrecord{$reckey} = 'correct_by_override';
                   3469: 		}
                   3470: 	    }	    
                   3471: 	    if ($submitter && 
1.259     banghart 3472: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3473: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3474: 	    }
1.259     banghart 3475: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3476: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3477: 	}
1.259     banghart 3478: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3479: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3480: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3481: 	        $dropMenu eq 'reset status')
                   3482: 	   {
1.524     raeburn  3483: 	    push(@version_parts,$new_part);
1.259     banghart 3484: 	}
1.41      ng       3485:     }
1.301     albertel 3486:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3487:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3488: 
1.344     albertel 3489:     if (%newrecord) {
                   3490:         if (@version_parts) {
1.364     banghart 3491:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3492:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3493: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3494: 	    foreach my $new_part (@version_parts) {
                   3495: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3496: 				$new_part,\%newrecord);
                   3497: 	    }
1.259     banghart 3498:         }
1.44      ng       3499: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3500: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3501: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3502: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3503:     }
1.269     raeburn  3504:     if ($aggregateflag) {
                   3505:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3506: 			      $cdom,$cnum);
1.269     raeburn  3507:     }
1.726     raeburn  3508:     return ('',$pts,$wgt,$totchg);
                   3509: }
                   3510: 
                   3511: sub makehidden {
1.728     raeburn  3512:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3513:     return unless (ref($record) eq 'HASH');
                   3514:     my %modified;
                   3515:     my $numchanged = 0;
                   3516:     if (exists($record->{$version.':keys'})) {
                   3517:         my $partsregexp = $parts;
                   3518:         $partsregexp =~ s/,/|/g;
                   3519:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3520:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3521:                  my $item = $1;
                   3522:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3523:                      $modified{$key} = $record->{$version.':'.$key};
                   3524:                  }
                   3525:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3526:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3527:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3528:                 $modified{$key} = $record->{$version.':'.$key};
                   3529:             }
                   3530:         }
                   3531:         if (keys(%modified)) {
                   3532:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3533:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3534:                 $numchanged ++;
                   3535:             }
                   3536:         }
                   3537:     }
                   3538:     return $numchanged;
1.36      ng       3539: }
1.322     albertel 3540: 
1.380     albertel 3541: sub check_and_remove_from_queue {
                   3542:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3543:     my @ungraded_parts;
                   3544:     foreach my $part (@{$parts}) {
                   3545: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3546: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3547: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3548: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3549: 		) {
                   3550: 	    push(@ungraded_parts, $part);
                   3551: 	}
                   3552:     }
                   3553:     if ( !@ungraded_parts ) {
                   3554: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3555: 					       $cnum,$domain,$stuname);
                   3556:     }
                   3557: }
                   3558: 
1.337     banghart 3559: sub handback_files {
                   3560:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3561:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3562:     my $res_error;
                   3563:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3564:     if ($res_error) {
                   3565:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3566:         return;
                   3567:     }
1.654     raeburn  3568:     my @handedback;
                   3569:     my $file_msg;
1.375     albertel 3570:     my @part_response_id = &flatten_responseType($responseType);
                   3571:     foreach my $part_response_id (@part_response_id) {
                   3572:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3573: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3574:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3575:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3576:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3577:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3578:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3579:                     my ($directory,$answer_file) = 
1.654     raeburn  3580:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3581:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3582: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3583: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3584:                     my $getpropath = 1;
1.773     raeburn  3585:                     my ($dir_list,$listerror) =
1.662     raeburn  3586:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3587:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3588: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3589:                     # fix filename
1.355     banghart 3590:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3591:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3592:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3593:             	                                $save_file_name);
1.337     banghart 3594:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3595:                         $request->print('<br /><span class="LC_error">'.
                   3596:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3597:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3598:                                         '</span>');
1.356     banghart 3599:                     } else {
1.360     banghart 3600:                         # mark the file as read only
1.654     raeburn  3601:                         push(@handedback,$save_file_name);
1.367     albertel 3602: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3603: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3604: 			}
                   3605:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3606: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3607:                     }
1.686     bisitz   3608:                     $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 3609:                 }
                   3610:             }
                   3611:         }
1.654     raeburn  3612:     }
                   3613:     if (@handedback > 0) {
                   3614:         $request->print('<br />');
                   3615:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3616:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3617:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3618:         my ($subject,$message);
                   3619:         if (scalar(@handedback) == 1) {
                   3620:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3621:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3622:         } else {
                   3623:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3624:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3625:         }
                   3626:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3627:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3628:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3629:         my ($feedurl,$showsymb) =
                   3630:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3631:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3632:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3633:         my $msgstatus =
                   3634:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3635:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3636:                  $restitle);
                   3637:         if ($msgstatus) {
                   3638:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3639:         }
                   3640:     }
1.338     banghart 3641:     return;
1.337     banghart 3642: }
                   3643: 
1.418     albertel 3644: sub get_feedurl_and_symb {
                   3645:     my ($symb,$uname,$udom) = @_;
                   3646:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3647:     $url = &Apache::lonnet::clutter($url);
                   3648:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3649: 					$symb,$udom,$uname);
                   3650:     if ($encrypturl =~ /^yes$/i) {
                   3651: 	&Apache::lonenc::encrypted(\$url,1);
                   3652: 	&Apache::lonenc::encrypted(\$symb,1);
                   3653:     }
                   3654:     return ($url,$symb);
                   3655: }
                   3656: 
1.313     banghart 3657: sub get_submitted_files {
                   3658:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3659:     my @files;
                   3660:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3661:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3662:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3663:     	    push(@files,$file_url.$file);
                   3664:         }
                   3665:     }
                   3666:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3667:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3668:     }
                   3669:     return (\@files);
                   3670: }
1.322     albertel 3671: 
1.269     raeburn  3672: # ----------- Provides number of tries since last reset.
                   3673: sub get_num_tries {
                   3674:     my ($record,$last_reset,$part) = @_;
                   3675:     my $timestamp = '';
                   3676:     my $num_tries = 0;
                   3677:     if ($$record{'version'}) {
                   3678:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3679:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3680:                 $timestamp = $$record{$version.':timestamp'};
                   3681:                 if ($timestamp > $last_reset) {
                   3682:                     $num_tries ++;
                   3683:                 } else {
                   3684:                     last;
                   3685:                 }
                   3686:             }
                   3687:         }
                   3688:     }
                   3689:     return $num_tries;
                   3690: }
                   3691: 
                   3692: # ----------- Determine decrements required in aggregate totals 
                   3693: sub decrement_aggs {
                   3694:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3695:     my %decrement = (
                   3696:                         attempts => 0,
                   3697:                         users => 0,
                   3698:                         correct => 0
                   3699:                     );
                   3700:     $decrement{'attempts'} = $aggtries;
                   3701:     if ($solvedstatus =~ /^correct/) {
                   3702:         $decrement{'correct'} = 1;
                   3703:     }
                   3704:     if ($aggtries == $totaltries) {
                   3705:         $decrement{'users'} = 1;
                   3706:     }
1.524     raeburn  3707:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3708:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3709:     }
                   3710:     return;
                   3711: }
                   3712: 
                   3713: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3714: sub get_last_resets {
1.270     albertel 3715:     my ($symb,$courseid,$partids) =@_;
                   3716:     my %last_resets;
1.269     raeburn  3717:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3718:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3719:     my @keys;
                   3720:     foreach my $part (@{$partids}) {
                   3721: 	push(@keys,"$symb\0$part\0resettime");
                   3722:     }
                   3723:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3724: 				     $cdom,$cname);
                   3725:     foreach my $part (@{$partids}) {
                   3726: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3727:     }
1.270     albertel 3728:     return %last_resets;
1.269     raeburn  3729: }
                   3730: 
1.251     banghart 3731: # ----------- Handles creating versions for portfolio files as answers
                   3732: sub version_portfiles {
1.343     banghart 3733:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3734:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3735:     my @returned_keys;
1.255     banghart 3736:     my $parts = join('|', @$parts_graded);
1.277     albertel 3737:     foreach my $key (keys(%$record)) {
1.259     banghart 3738:         my $new_portfiles;
1.263     banghart 3739:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3740:             my @versioned_portfiles;
1.367     albertel 3741:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3742:             if (@portfiles) {
                   3743:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3744:                                                       \@versioned_portfiles);
1.252     banghart 3745:             }
1.343     banghart 3746:             $$record{$key} = join(',',@versioned_portfiles);
                   3747:             push(@returned_keys,$key);
1.251     banghart 3748:         }
                   3749:     } 
1.343     banghart 3750:     return (@returned_keys);   
1.305     banghart 3751: }
                   3752: 
1.44      ng       3753: #--------------------------------------------------------------------------------------
                   3754: #
                   3755: #-------------------------- Next few routines handles grading by section or whole class
                   3756: #
                   3757: #--- Javascript to handle grading by section or whole class
1.42      ng       3758: sub viewgrades_js {
                   3759:     my ($request) = shift;
                   3760: 
1.539     riegler  3761:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3762:     &js_escape(\$alertmsg);
1.597     wenzelju 3763:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3764:    function writePoint(partid,weight,point) {
1.125     ng       3765: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3766: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3767: 	if (point == "textval") {
1.125     ng       3768: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3769: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3770: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3771: 		var resetbox = false;
                   3772: 		for (var i=0; i<radioButton.length; i++) {
                   3773: 		    if (radioButton[i].checked) {
                   3774: 			textbox.value = i;
                   3775: 			resetbox = true;
                   3776: 		    }
                   3777: 		}
                   3778: 		if (!resetbox) {
                   3779: 		    textbox.value = "";
                   3780: 		}
                   3781: 		return;
                   3782: 	    }
1.109     matthew  3783: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3784: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3785: 				   ") greater than the weight for the part. Accept?");
                   3786: 		if (resp == false) {
                   3787: 		    textbox.value = "";
                   3788: 		    return;
                   3789: 		}
                   3790: 	    }
1.42      ng       3791: 	    for (var i=0; i<radioButton.length; i++) {
                   3792: 		radioButton[i].checked=false;
1.109     matthew  3793: 		if (parseFloat(point) == i) {
1.42      ng       3794: 		    radioButton[i].checked=true;
                   3795: 		}
                   3796: 	    }
1.41      ng       3797: 
1.42      ng       3798: 	} else {
1.125     ng       3799: 	    textbox.value = parseFloat(point);
1.42      ng       3800: 	}
1.41      ng       3801: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3802: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3803: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3804: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3805: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3806: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3807: 	    if (saveval != "correct") {
                   3808: 		scorename.value = point;
1.43      ng       3809: 		if (selname[0].selected != true) {
                   3810: 		    selname[0].selected = true;
                   3811: 		}
1.42      ng       3812: 	    }
                   3813: 	}
1.125     ng       3814: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3815:     }
                   3816: 
                   3817:     function writeRadText(partid,weight) {
1.125     ng       3818: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3819: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3820:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3821: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3822: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3823: 	    for (var i=0; i<radioButton.length; i++) {
                   3824: 		radioButton[i].checked=false;
                   3825: 
                   3826: 	    }
                   3827: 	    textbox.value = "";
                   3828: 
                   3829: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3830: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3831: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3832: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3833: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3834: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3835: 		if ((saveval != "correct") || override) {
1.42      ng       3836: 		    scorename.value = "";
1.125     ng       3837: 		    if (selval[1].selected) {
                   3838: 			selname[1].selected = true;
                   3839: 		    } else {
                   3840: 			selname[2].selected = true;
                   3841: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3842: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3843: 		    }
1.42      ng       3844: 		}
                   3845: 	    }
1.43      ng       3846: 	} else {
                   3847: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3848: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3849: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3850: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3851: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3852: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3853: 		if ((saveval != "correct") || override) {
1.125     ng       3854: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3855: 		    selname[0].selected = true;
                   3856: 		}
                   3857: 	    }
                   3858: 	}	    
1.42      ng       3859:     }
                   3860: 
                   3861:     function changeSelect(partid,user) {
1.125     ng       3862: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3863: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3864: 	var point  = textbox.value;
1.125     ng       3865: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3866: 
1.109     matthew  3867: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3868: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3869: 	    textbox.value = "";
                   3870: 	    return;
                   3871: 	}
1.109     matthew  3872: 	if (parseFloat(point) > parseFloat(weight)) {
                   3873: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3874: 			       ") greater than the weight of the part. Accept?");
                   3875: 	    if (resp == false) {
                   3876: 		textbox.value = "";
                   3877: 		return;
                   3878: 	    }
                   3879: 	}
1.42      ng       3880: 	selval[0].selected = true;
                   3881:     }
                   3882: 
                   3883:     function changeOneScore(partid,user) {
1.125     ng       3884: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3885: 	if (selval[1].selected || selval[2].selected) {
                   3886: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3887: 	    if (selval[2].selected) {
                   3888: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3889: 	    }
1.269     raeburn  3890:         }
1.42      ng       3891:     }
                   3892: 
                   3893:     function resetEntry(numpart) {
                   3894: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3895: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3896: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3897: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3898: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3899: 	    for (var i=0; i<radioButton.length; i++) {
                   3900: 		radioButton[i].checked=false;
                   3901: 
                   3902: 	    }
                   3903: 	    textbox.value = "";
                   3904: 	    selval[0].selected = true;
                   3905: 
                   3906: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3907: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3908: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3909: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3910: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3911: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3912: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3913: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3914: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3915: 		if (saveselval == "excused") {
1.43      ng       3916: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3917: 		} else {
1.43      ng       3918: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3919: 		}
                   3920: 	    }
1.41      ng       3921: 	}
1.42      ng       3922:     }
                   3923: 
1.41      ng       3924: VIEWJAVASCRIPT
1.42      ng       3925: }
                   3926: 
1.44      ng       3927: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3928: sub viewgrades {
1.608     www      3929:     my ($request,$symb) = @_;
1.745     raeburn  3930:     my ($is_tool,$toolsymb);
                   3931:     if ($symb =~ /ext\.tool$/) {
                   3932:         $is_tool = 1;
                   3933:         $toolsymb = $symb;
                   3934:     }
1.42      ng       3935:     &viewgrades_js($request);
1.41      ng       3936: 
1.168     albertel 3937:     #need to make sure we have the correct data for later EXT calls, 
                   3938:     #thus invalidate the cache
                   3939:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3940:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3941:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3942:     &Apache::lonnet::clear_EXT_cache_status();
                   3943: 
1.398     albertel 3944:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3945: 
                   3946:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3947:     $result.=&jscriptNform($symb);
1.41      ng       3948: 
1.44      ng       3949:     #beginning of class grading form
1.442     banghart 3950:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3951:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3952: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3953: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3954: 	&build_section_inputs().
1.442     banghart 3955: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3956: 
1.738     raeburn  3957:     #retrieve selected groups
                   3958:     my (@groups,$group_display);
                   3959:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3960:     if (grep(/^all$/,@groups)) {
                   3961:         @groups = ('all');
                   3962:     } elsif (grep(/^none$/,@groups)) {
                   3963:         @groups = ('none');
                   3964:     } elsif (@groups > 0) {
                   3965:         $group_display = join(', ',@groups);
                   3966:     }
                   3967: 
                   3968:     my ($common_header,$specific_header,@sections,$section_display);
                   3969:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3970:     if (grep(/^all$/,@sections)) {
                   3971:         @sections = ('all');
                   3972:         if ($group_display) {
                   3973:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3974:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3975:         } elsif (grep(/^none$/,@groups)) {
                   3976:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3977:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3978:         } else {
                   3979: 	    $common_header = &mt('Assign Common Grade to Class');
                   3980:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3981:         }
                   3982:     } elsif (grep(/^none$/,@sections)) {
                   3983:         @sections = ('none');
                   3984:         if ($group_display) {
                   3985:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3986:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3987:         } elsif (grep(/^none$/,@groups)) {
                   3988:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3989:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3990:         } else {
                   3991:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3992: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3993:         }
                   3994:     } else {
                   3995:         $section_display = join (", ",@sections);
                   3996:         if ($group_display) {
                   3997:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3998:                                  $section_display,$group_display);
                   3999:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4000:                                    $section_display,$group_display);
                   4001:         } elsif (grep(/^none$/,@groups)) {
                   4002:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4003:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4004:         } else {
                   4005:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4006: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4007:         }
                   4008:     }
                   4009:     my %submit_types = &substatus_options();
                   4010:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4011: 
                   4012:     if ($env{'form.submitonly'} eq 'all') {
                   4013:         $result.= '<h3>'.$common_header.'</h3>';
                   4014:     } else {
1.745     raeburn  4015:         my $text;
                   4016:         if ($is_tool) {
                   4017:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4018:         } else {
                   4019:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4020:         }
                   4021:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4022:     }
1.738     raeburn  4023:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4024:     #radio buttons/text box for assigning points for a section or class.
                   4025:     #handles different parts of a problem
1.582     raeburn  4026:     my $res_error;
                   4027:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4028:     if ($res_error) {
                   4029:         return &navmap_errormsg();
                   4030:     }
1.42      ng       4031:     my %weight = ();
                   4032:     my $ctsparts = 0;
1.45      ng       4033:     my %seen = ();
1.745     raeburn  4034:     my @part_response_id;
                   4035:     if ($is_tool) {
                   4036:         @part_response_id = ([0,'']);
                   4037:     } else {
                   4038:         @part_response_id = &flatten_responseType($responseType);
                   4039:     }
1.375     albertel 4040:     foreach my $part_response_id (@part_response_id) {
                   4041:     	my ($partid,$respid) = @{ $part_response_id };
                   4042: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4043: 	next if $seen{$partid};
                   4044: 	$seen{$partid}++;
1.42      ng       4045: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4046: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4047: 
1.324     albertel 4048: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4049: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4050: 	my $ctr = 0;
1.42      ng       4051: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4052: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4053: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4054: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4055: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4056: 	    $ctr++;
                   4057: 	}
1.485     albertel 4058: 	$radio.='</tr></table>';
                   4059: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4060: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4061: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4062: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4063:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4064:             '<select name="SELVAL_'.$partid.'" '.
                   4065:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4066:                 $weight{$partid}.')"> '.
1.401     albertel 4067: 	    '<option selected="selected"> </option>'.
1.485     albertel 4068: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4069: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4070: 	    '</select></td>'.
                   4071:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4072: 	$line.='<input type="hidden" name="partid_'.
                   4073: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4074: 	$line.='<input type="hidden" name="weight_'.
                   4075: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4076: 
                   4077: 	$result.=
                   4078: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4079: 	    '<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 4080: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4081: 	$ctsparts++;
1.41      ng       4082:     }
1.474     albertel 4083:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4084: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4085:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4086: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4087: 
1.44      ng       4088:     #table listing all the students in a section/class
                   4089:     #header of table
1.738     raeburn  4090:     if ($env{'form.submitonly'} eq 'all') {
                   4091:         $result.= '<h3>'.$specific_header.'</h3>';
                   4092:     } else {
1.745     raeburn  4093:         my $text;
                   4094:         if ($is_tool) {
                   4095:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4096:         } else {
                   4097:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4098:         }
                   4099:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4100:     }
                   4101:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4102: 	      &Apache::loncommon::start_data_table_header_row().
                   4103: 	      '<th>'.&mt('No.').'</th>'.
                   4104: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4105:     my $partserror;
                   4106:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4107:     if ($partserror) {
                   4108:         return &navmap_errormsg();
                   4109:     }
1.324     albertel 4110:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4111:     my @partids = ();
1.41      ng       4112:     foreach my $part (@parts) {
1.745     raeburn  4113: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4114:         my $narrowtext = &mt('Tries');
                   4115: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4116: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4117: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4118:         push(@partids,$partid);
1.628     www      4119: #
                   4120: # FIXME: Looks like $display looks at English text
                   4121: #
1.324     albertel 4122: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4123: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4124: 	    $result.='<th>'.
1.697     bisitz   4125: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4126: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4127: 	    next;
1.485     albertel 4128: 	    
1.207     albertel 4129: 	} else {
1.485     albertel 4130: 	    if ($display =~ /Problem Status/) {
                   4131: 		my $grade_status_mt = &mt('Grade Status');
                   4132: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4133: 	    }
                   4134: 	    my $part_mt = &mt('Part:');
                   4135: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4136: 	}
1.485     albertel 4137: 
1.474     albertel 4138: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4139:     }
1.474     albertel 4140:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4141: 
1.270     albertel 4142:     my %last_resets = 
                   4143: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4144: 
1.41      ng       4145:     #get info for each student
1.44      ng       4146:     #list all the students - with points and grade status
1.738     raeburn  4147:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4148:     my $ctr = 0;
1.294     albertel 4149:     foreach (sort 
                   4150: 	     {
                   4151: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4152: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4153: 		 }
                   4154: 		 return $a cmp $b;
                   4155: 	     } (keys(%$fullname))) {
1.324     albertel 4156: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4157: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4158:     }
1.474     albertel 4159:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4160:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4161:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4162: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4163:     if ($ctr == 0) {
1.442     banghart 4164:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4165:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4166:                 '<span class="LC_warning">';
                   4167:         if ($env{'form.submitonly'} eq 'all') {
                   4168:             if (grep(/^all$/,@sections)) {
                   4169:                 if (grep(/^all$/,@groups)) {
                   4170:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4171:                                    $stu_status);
                   4172:                 } elsif (grep(/^none$/,@groups)) {
                   4173:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4174:                                    $stu_status); 
                   4175:                 } else {
                   4176:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4177:                                    $group_display,$stu_status);
                   4178:                 }
                   4179:             } elsif (grep(/^none$/,@sections)) {
                   4180:                 if (grep(/^all$/,@groups)) {
                   4181:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4182:                                    $stu_status);
                   4183:                 } elsif (grep(/^none$/,@groups)) {
                   4184:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4185:                                    $stu_status);
                   4186:                 } else {
                   4187:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4188:                                    $group_display,$stu_status);
                   4189:                 }
                   4190:             } else {
                   4191:                 if (grep(/^all$/,@groups)) {
                   4192:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4193:                                    $section_display,$stu_status);
                   4194:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4195:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4196:                                    $section_display,$stu_status);
                   4197:                 } else {
                   4198:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4199:                                    $section_display,$group_display,$stu_status);
                   4200:                 }
                   4201:             }
                   4202:         } else {
                   4203:             if (grep(/^all$/,@sections)) {
                   4204:                 if (grep(/^all$/,@groups)) {
                   4205:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4206:                                    $stu_status,$submission_status);
                   4207:                 } elsif (grep(/^none$/,@groups)) {
                   4208:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4209:                                    $stu_status,$submission_status);
                   4210:                 } else {
                   4211:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4212:                                    $group_display,$stu_status,$submission_status);
                   4213:                 }
                   4214:             } elsif (grep(/^none$/,@sections)) {
                   4215:                 if (grep(/^all$/,@groups)) {
                   4216:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4217:                                    $stu_status,$submission_status);
                   4218:                 } elsif (grep(/^none$/,@groups)) {
                   4219:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4220:                                    $stu_status,$submission_status);
                   4221:                 } else {
                   4222:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4223:                                    $group_display,$stu_status,$submission_status);
                   4224:                 }
                   4225:             } else {
                   4226:                 if (grep(/^all$/,@groups)) {
                   4227: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4228: 	                           $section_display,$stu_status,$submission_status);
                   4229:                 } elsif (grep(/^none$/,@groups)) {
                   4230:                     $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.',
                   4231:                                    $section_display,$stu_status,$submission_status);
                   4232:                 } else {
                   4233:                     $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.',
                   4234:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4235:                 }
                   4236:             }
                   4237:         }
                   4238: 	$result .= '</span><br />';
1.96      albertel 4239:     }
1.41      ng       4240:     return $result;
                   4241: }
                   4242: 
1.738     raeburn  4243: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4244: sub viewstudentgrade {
1.745     raeburn  4245:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4246:     my ($uname,$udom) = split(/:/,$student);
                   4247:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4248:     my $submitonly = $env{'form.submitonly'};
                   4249:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4250:         my %partstatus = ();
                   4251:         if (ref($parts) eq 'ARRAY') {
                   4252:             foreach my $apart (@{$parts}) {
                   4253:                 my ($part,$type) = &split_part_type($apart);
                   4254:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4255:                 $status = 'nothing' if ($status eq '');
                   4256:                 $partstatus{$part}      = $status;
                   4257:                 my $subkey = "resource.$part.submitted_by";
                   4258:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4259:             }
                   4260:             my $submitted = 0;
                   4261:             my $graded = 0;
                   4262:             my $incorrect = 0;
                   4263:             foreach my $key (keys(%partstatus)) {
                   4264:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4265:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4266:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4267: 
                   4268:                 my $partid = (split(/\./,$key))[1];
                   4269:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4270:                     $submitted = 0;
                   4271:                 }
                   4272:             }
                   4273:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4274:                                        $submitonly eq 'incorrect' ||
                   4275:                                        $submitonly eq 'graded'));
                   4276:             return if (!$graded && ($submitonly eq 'graded'));
                   4277:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4278:         }
                   4279:     }
                   4280:     if ($submitonly eq 'queued') {
                   4281:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4282:         my %queue_status =
                   4283:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4284:                                                     $udom,$uname);
                   4285:         return if (!defined($queue_status{'gradingqueue'}));
                   4286:     }
                   4287:     $$ctr++;
                   4288:     my %aggregates = ();
1.474     albertel 4289:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4290: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4291: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4292: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4293: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4294: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4295:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4296:     foreach my $apart (@$parts) {
                   4297: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4298: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4299:         $result.='<td align="center">';
1.269     raeburn  4300:         my ($aggtries,$totaltries);
                   4301:         unless (exists($aggregates{$part})) {
1.270     albertel 4302: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4303: 	    $aggtries = $totaltries;
1.269     raeburn  4304:             if ($$last_resets{$part}) {  
1.270     albertel 4305:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4306: 					   $part);
                   4307:             }
1.269     raeburn  4308:             $result.='<input type="hidden" name="'.
                   4309:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4310:             $result.='<input type="hidden" name="'.
                   4311:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4312:             $aggregates{$part} = 1;
                   4313:         }
1.41      ng       4314: 	if ($type eq 'awarded') {
1.320     albertel 4315: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4316: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4317: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4318: 	    $result.='<input type="text" name="'.
1.89      albertel 4319: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4320:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4321: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4322: 	} elsif ($type eq 'solved') {
                   4323: 	    my ($status,$foo)=split(/_/,$score,2);
                   4324: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4325: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4326: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4327: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4328: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4329:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4330: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4331: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4332: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4333: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4334: 	} else {
                   4335: 	    $result.='<input type="hidden" name="'.
                   4336: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4337: 		    "\n";
1.233     albertel 4338: 	    $result.='<input type="text" name="'.
1.122     ng       4339: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4340: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4341: 	}
                   4342:     }
1.474     albertel 4343:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4344:     return $result;
1.38      ng       4345: }
                   4346: 
1.44      ng       4347: #--- change scores for all the students in a section/class
                   4348: #    record does not get update if unchanged
1.38      ng       4349: sub editgrades {
1.608     www      4350:     my ($request,$symb) = @_;
1.745     raeburn  4351:     my $toolsymb;
                   4352:     if ($symb =~ /ext\.tool$/) {
                   4353:         $toolsymb = $symb;
                   4354:     }
1.41      ng       4355: 
1.433     banghart 4356:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4357:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4358:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4359: 
1.477     albertel 4360:     my $result= &Apache::loncommon::start_data_table().
                   4361: 	&Apache::loncommon::start_data_table_header_row().
                   4362: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4363: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4364:     my %scoreptr = (
                   4365: 		    'correct'  =>'correct_by_override',
                   4366: 		    'incorrect'=>'incorrect_by_override',
                   4367: 		    'excused'  =>'excused',
                   4368: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4369:                     'credited' =>'credit_attempted',
1.43      ng       4370: 		    'nothing'  => '',
                   4371: 		    );
1.257     albertel 4372:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4373: 
1.44      ng       4374:     my (@partid);
                   4375:     my %weight = ();
1.54      albertel 4376:     my %columns = ();
1.44      ng       4377:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4378: 
1.582     raeburn  4379:     my $partserror;
                   4380:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4381:     if ($partserror) {
                   4382:         return &navmap_errormsg();
                   4383:     }
1.54      albertel 4384:     my $header;
1.257     albertel 4385:     while ($ctr < $env{'form.totalparts'}) {
                   4386: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4387: 	push(@partid,$partid);
1.257     albertel 4388: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4389: 	$ctr++;
1.54      albertel 4390:     }
1.324     albertel 4391:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4392:     my $totcolspan = 0;
1.54      albertel 4393:     foreach my $partid (@partid) {
1.478     albertel 4394: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4395: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4396: 	$columns{$partid}=2;
                   4397: 	foreach my $stores (@parts) {
                   4398: 	    my ($part,$type) = &split_part_type($stores);
                   4399: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4400: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4401: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4402: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4403:             my $narrowtext = &mt('Tries');
                   4404: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4405: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4406: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4407: 	    $columns{$partid}+=2;
                   4408: 	}
1.748     raeburn  4409:         $totcolspan += $columns{$partid};
1.54      albertel 4410:     }
                   4411:     foreach my $partid (@partid) {
1.324     albertel 4412: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4413: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4414: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4415: 	    '</th>';
1.54      albertel 4416: 
1.44      ng       4417:     }
1.477     albertel 4418:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4419: 	&Apache::loncommon::start_data_table_header_row().
                   4420: 	$header.
                   4421: 	&Apache::loncommon::end_data_table_header_row();
                   4422:     my @noupdate;
1.126     ng       4423:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4424:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4425: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4426: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4427: 	my %newrecord;
                   4428: 	my $updateflag = 0;
1.108     albertel 4429: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4430: 	my $canmodify = &canmodify($usec);
                   4431: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4432: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4433: 	if (!$canmodify) {
1.477     albertel 4434: 	    push(@noupdate,
1.748     raeburn  4435: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4436: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4437: 	    next;
                   4438: 	}
1.269     raeburn  4439:         my %aggregate = ();
                   4440:         my $aggregateflag = 0;
1.281     albertel 4441: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4442: 	foreach (@partid) {
1.257     albertel 4443: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4444: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4445: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4446: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4447: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4448: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4449: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4450: 	    my $score;
                   4451: 	    if ($partial eq '') {
1.257     albertel 4452: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4453: 	    } elsif ($partial > 0) {
                   4454: 		$score = 'correct_by_override';
                   4455: 	    } elsif ($partial == 0) {
                   4456: 		$score = 'incorrect_by_override';
                   4457: 	    }
1.257     albertel 4458: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4459: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4460: 
1.292     albertel 4461: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4462: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4463: 	    if ($dropMenu eq 'reset status' &&
                   4464: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4465: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4466: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4467: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4468: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4469: 		$updateflag = 1;
1.269     raeburn  4470:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4471:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4472:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4473:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4474:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4475:                     $aggregateflag = 1;
                   4476:                 }
1.139     albertel 4477: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4478: 		$updateflag = 1;
                   4479: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4480: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4481: 		$rec_update++;
1.125     ng       4482: 	    }
                   4483: 
1.93      albertel 4484: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4485: 		'<td align="center">'.$awarded.
                   4486: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4487: 
1.54      albertel 4488: 
                   4489: 	    my $partid=$_;
                   4490: 	    foreach my $stores (@parts) {
                   4491: 		my ($part,$type) = &split_part_type($stores);
                   4492: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4493: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4494: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4495: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4496: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4497: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4498: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4499: 		    $updateflag=1;
                   4500: 		}
1.93      albertel 4501: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4502: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4503: 	    }
1.44      ng       4504: 	}
1.477     albertel 4505: 	$line.="\n";
1.301     albertel 4506: 
                   4507: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4508: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4509: 
1.44      ng       4510: 	if ($updateflag) {
                   4511: 	    $count++;
1.257     albertel 4512: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4513: 				    $udom,$uname);
1.301     albertel 4514: 
                   4515: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4516: 					      $cnum,$udom,$uname)) {
                   4517: 		# need to figure out if should be in queue.
                   4518: 		my %record =  
                   4519: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4520: 					     $udom,$uname);
                   4521: 		my $all_graded = 1;
                   4522: 		my $none_graded = 1;
                   4523: 		foreach my $part (@parts) {
                   4524: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4525: 			$all_graded = 0;
                   4526: 		    } else {
                   4527: 			$none_graded = 0;
                   4528: 		    }
                   4529: 		}
                   4530: 
                   4531: 		if ($all_graded || $none_graded) {
                   4532: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4533: 							   $symb,$cdom,$cnum,
                   4534: 							   $udom,$uname);
                   4535: 		}
                   4536: 	    }
                   4537: 
1.477     albertel 4538: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4539: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4540: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4541: 	    $updateCtr++;
1.93      albertel 4542: 	} else {
1.477     albertel 4543: 	    push(@noupdate,
                   4544: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4545: 	    $noupdateCtr++;
1.44      ng       4546: 	}
1.269     raeburn  4547:         if ($aggregateflag) {
                   4548:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4549: 				  $cdom,$cnum);
1.269     raeburn  4550:         }
1.93      albertel 4551:     }
1.477     albertel 4552:     if (@noupdate) {
1.748     raeburn  4553:         my $numcols=$totcolspan+2;
1.477     albertel 4554: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4555: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4556: 	    &mt('No Changes Occurred For the Students Below').
                   4557: 	    '</td>'.
1.477     albertel 4558: 	    &Apache::loncommon::end_data_table_row();
                   4559: 	foreach my $line (@noupdate) {
                   4560: 	    $result.=
                   4561: 		&Apache::loncommon::start_data_table_row().
                   4562: 		$line.
                   4563: 		&Apache::loncommon::end_data_table_row();
                   4564: 	}
1.44      ng       4565:     }
1.614     www      4566:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4567:     my $msg = '<p><b>'.
                   4568: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4569: 	    $rec_update,$count).'</b><br />'.
                   4570: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4571: 	'</b></p>';
1.44      ng       4572:     return $title.$msg.$result;
1.5       albertel 4573: }
1.54      albertel 4574: 
                   4575: sub split_part_type {
                   4576:     my ($partstr) = @_;
                   4577:     my ($temp,@allparts)=split(/_/,$partstr);
                   4578:     my $type=pop(@allparts);
1.439     albertel 4579:     my $part=join('_',@allparts);
1.54      albertel 4580:     return ($part,$type);
                   4581: }
                   4582: 
1.44      ng       4583: #------------- end of section for handling grading by section/class ---------
                   4584: #
                   4585: #----------------------------------------------------------------------------
                   4586: 
1.5       albertel 4587: 
1.44      ng       4588: #----------------------------------------------------------------------------
                   4589: #
                   4590: #-------------------------- Next few routines handles grading by csv upload
                   4591: #
                   4592: #--- Javascript to handle csv upload
1.27      albertel 4593: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4594:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4595:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4596:   &js_escape(\$error1);
                   4597:   &js_escape(\$error2);
1.27      albertel 4598:   return(<<ENDPICK);
                   4599:   function verify(vf) {
                   4600:     var foundsomething=0;
                   4601:     var founduname=0;
1.243     albertel 4602:     var foundID=0;
1.743     raeburn  4603:     var foundclicker=0;
1.27      albertel 4604:     for (i=0;i<=vf.nfields.value;i++) {
                   4605:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4606:       if (i==0 && tw!=0) { foundID=1; }
                   4607:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4608:       if (i==2 && tw!=0) { foundclicker=1; }
                   4609:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4610:     }
1.743     raeburn  4611:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4612: 	alert('$error1');
                   4613: 	return;
1.27      albertel 4614:     }
                   4615:     if (foundsomething==0) {
1.246     albertel 4616: 	alert('$error2');
                   4617: 	return;
1.27      albertel 4618:     }
                   4619:     vf.submit();
                   4620:   }
                   4621:   function flip(vf,tf) {
                   4622:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4623:     var i;
                   4624:     for (i=0;i<=vf.nfields.value;i++) {
                   4625:       //can not pick the same destination field for both name and domain
                   4626:       if (((i ==0)||(i ==1)) && 
                   4627:           ((tf==0)||(tf==1)) && 
                   4628:           (i!=tf) &&
                   4629:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4630:         eval('vf.f'+i+'.selectedIndex=0;')
                   4631:       }
                   4632:     }
                   4633:   }
                   4634: ENDPICK
                   4635: }
                   4636: 
                   4637: sub csvupload_javascript_forward_associate {
1.743     raeburn  4638:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4639:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4640:   &js_escape(\$error1);
                   4641:   &js_escape(\$error2);
1.27      albertel 4642:   return(<<ENDPICK);
                   4643:   function verify(vf) {
                   4644:     var foundsomething=0;
                   4645:     var founduname=0;
1.243     albertel 4646:     var foundID=0;
1.743     raeburn  4647:     var foundclicker=0;
1.27      albertel 4648:     for (i=0;i<=vf.nfields.value;i++) {
                   4649:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4650:       if (tw==1) { foundID=1; }
                   4651:       if (tw==2) { founduname=1; }
1.745     raeburn  4652:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4653:       if (tw>4) { foundsomething=1; }
1.27      albertel 4654:     }
1.743     raeburn  4655:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4656: 	alert('$error1');
                   4657: 	return;
1.27      albertel 4658:     }
                   4659:     if (foundsomething==0) {
1.246     albertel 4660: 	alert('$error2');
                   4661: 	return;
1.27      albertel 4662:     }
                   4663:     vf.submit();
                   4664:   }
                   4665:   function flip(vf,tf) {
                   4666:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4667:     var i;
                   4668:     //can not pick the same destination field twice
                   4669:     for (i=0;i<=vf.nfields.value;i++) {
                   4670:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4671:         eval('vf.f'+i+'.selectedIndex=0;')
                   4672:       }
                   4673:     }
                   4674:   }
                   4675: ENDPICK
                   4676: }
                   4677: 
1.26      albertel 4678: sub csvuploadmap_header {
1.324     albertel 4679:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4680:     my $javascript;
1.257     albertel 4681:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4682: 	$javascript=&csvupload_javascript_reverse_associate();
                   4683:     } else {
                   4684: 	$javascript=&csvupload_javascript_forward_associate();
                   4685:     }
1.45      ng       4686: 
1.418     albertel 4687:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4688:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4689:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4690:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4691:     my $reverse=&mt("Reverse Association");
1.41      ng       4692:     $request->print(<<ENDPICK);
1.632     www      4693: <br />
                   4694: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4695: <input type="hidden" name="associate"  value="" />
                   4696: <input type="hidden" name="phase"      value="three" />
                   4697: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4698: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4699: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4700: <input type="hidden" name="upfile_associate" 
1.257     albertel 4701:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4702: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4703: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4704: <hr />
                   4705: ENDPICK
1.597     wenzelju 4706:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4707:     return '';
1.26      albertel 4708: 
                   4709: }
                   4710: 
                   4711: sub csvupload_fields {
1.582     raeburn  4712:     my ($symb,$errorref) = @_;
1.745     raeburn  4713:     my $toolsymb;
                   4714:     if ($symb =~ /ext\.tool$/) {
                   4715:         $toolsymb = $symb;
                   4716:     }
1.582     raeburn  4717:     my (@parts) = &getpartlist($symb,$errorref);
                   4718:     if (ref($errorref)) {
                   4719:         if ($$errorref) {
                   4720:             return;
                   4721:         }
                   4722:     }
                   4723: 
1.556     weissno  4724:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4725: 		['username','Student Username'],
1.743     raeburn  4726: 		['clicker','Clicker ID'],
1.243     albertel 4727: 		['domain','Student Domain']);
1.324     albertel 4728:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4729:     foreach my $part (sort(@parts)) {
                   4730: 	my @datum;
1.745     raeburn  4731: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4732: 	my $name=$part;
1.745     raeburn  4733: 	if (!$display) { $display = $name; }
1.41      ng       4734: 	@datum=($name,$display);
1.244     albertel 4735: 	if ($name=~/^stores_(.*)_awarded/) {
                   4736: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4737: 	}
1.41      ng       4738: 	push(@fields,\@datum);
                   4739:     }
                   4740:     return (@fields);
1.26      albertel 4741: }
                   4742: 
                   4743: sub csvuploadmap_footer {
1.41      ng       4744:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4745:     my $buttontext = &mt('Assign Grades');
1.41      ng       4746:     $request->print(<<ENDPICK);
1.26      albertel 4747: </table>
                   4748: <input type="hidden" name="nfields" value="$i" />
                   4749: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4750: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4751: </form>
                   4752: ENDPICK
                   4753: }
                   4754: 
1.283     albertel 4755: sub checkforfile_js {
1.638     www      4756:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4757:     &js_escape(\$alertmsg);
1.597     wenzelju 4758:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4759:     function checkUpload(formname) {
                   4760: 	if (formname.upfile.value == "") {
1.539     riegler  4761: 	    alert("$alertmsg");
1.86      ng       4762: 	    return false;
                   4763: 	}
                   4764: 	formname.submit();
                   4765:     }
                   4766: CSVFORMJS
1.283     albertel 4767:     return $result;
                   4768: }
                   4769: 
                   4770: sub upcsvScores_form {
1.608     www      4771:     my ($request,$symb) = @_;
1.283     albertel 4772:     if (!$symb) {return '';}
                   4773:     my $result=&checkforfile_js();
1.632     www      4774:     $result.=&Apache::loncommon::start_data_table().
                   4775:              &Apache::loncommon::start_data_table_header_row().
                   4776:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4777:              &Apache::loncommon::end_data_table_header_row().
                   4778:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4779:     my $upload=&mt("Upload Scores");
1.86      ng       4780:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4781:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4782:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4783:     $result.=<<ENDUPFORM;
1.106     albertel 4784: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4785: <input type="hidden" name="symb" value="$symb" />
                   4786: <input type="hidden" name="command" value="csvuploadmap" />
                   4787: $upfile_select
1.589     bisitz   4788: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4789: </form>
                   4790: ENDUPFORM
1.370     www      4791:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4792:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4793:              '</td>'.
                   4794:             &Apache::loncommon::end_data_table_row().
                   4795:             &Apache::loncommon::end_data_table();
1.86      ng       4796:     return $result;
                   4797: }
                   4798: 
                   4799: 
1.26      albertel 4800: sub csvuploadmap {
1.768     raeburn  4801:     my ($request,$symb) = @_;
1.41      ng       4802:     if (!$symb) {return '';}
1.72      ng       4803: 
1.41      ng       4804:     my $datatoken;
1.257     albertel 4805:     if (!$env{'form.datatoken'}) {
1.41      ng       4806: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4807:     } else {
1.742     raeburn  4808: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4809:         if ($datatoken ne '') {
                   4810: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4811:         }
1.26      albertel 4812:     }
1.41      ng       4813:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4814:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4815:     my ($i,$keyfields);
                   4816:     if (@records) {
1.582     raeburn  4817:         my $fieldserror;
                   4818: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4819:         if ($fieldserror) {
                   4820:             $request->print(&navmap_errormsg());
                   4821:             return;
                   4822:         }
1.257     albertel 4823: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4824: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4825: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4826: 							  \@fields);
                   4827: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4828: 	    chop($keyfields);
                   4829: 	} else {
                   4830: 	    unshift(@fields,['none','']);
                   4831: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4832: 							    \@fields);
1.311     banghart 4833:             foreach my $rec (@records) {
                   4834:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4835:                 if (%temp) {
                   4836:                     $keyfields=join(',',sort(keys(%temp)));
                   4837:                     last;
                   4838:                 }
                   4839:             }
1.41      ng       4840: 	}
                   4841:     }
                   4842:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4843: 
1.41      ng       4844:     return '';
1.27      albertel 4845: }
                   4846: 
1.246     albertel 4847: sub csvuploadoptions {
1.608     www      4848:     my ($request,$symb)= @_;
1.632     www      4849:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4850:     $request->print(<<ENDPICK);
                   4851: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4852: <input type="hidden" name="command"    value="csvuploadassign" />
                   4853: <p>
                   4854: <label>
                   4855:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4856:    $overwrite
1.246     albertel 4857: </label>
                   4858: </p>
                   4859: ENDPICK
                   4860:     my %fields=&get_fields();
                   4861:     if (!defined($fields{'domain'})) {
1.257     albertel 4862: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4863: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4864:     }
1.257     albertel 4865:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4866: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4867: 	my $cleankey=$1;
                   4868: 	if ($cleankey eq 'command') { next; }
                   4869: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4870: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4871:     }
                   4872:     # FIXME do a check for any duplicated user ids...
                   4873:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4874:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4875: <hr /></form>'."\n");
1.246     albertel 4876:     return '';
                   4877: }
                   4878: 
                   4879: sub get_fields {
                   4880:     my %fields;
1.257     albertel 4881:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4882:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4883: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4884: 	    if ($env{'form.f'.$i} ne 'none') {
                   4885: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4886: 	    }
                   4887: 	} else {
1.257     albertel 4888: 	    if ($env{'form.f'.$i} ne 'none') {
                   4889: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4890: 	    }
                   4891: 	}
1.27      albertel 4892:     }
1.246     albertel 4893:     return %fields;
                   4894: }
                   4895: 
                   4896: sub csvuploadassign {
1.766     raeburn  4897:     my ($request,$symb) = @_;
1.246     albertel 4898:     if (!$symb) {return '';}
1.345     bowersj2 4899:     my $error_msg = '';
1.742     raeburn  4900:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4901:     if ($datatoken ne '') { 
                   4902:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4903:     }
1.246     albertel 4904:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4905:     my %fields=&get_fields();
1.257     albertel 4906:     my $courseid=$env{'request.course.id'};
1.97      albertel 4907:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4908:     my @notallowed;
1.41      ng       4909:     my @skipped;
1.657     raeburn  4910:     my @warnings;
1.41      ng       4911:     my $countdone=0;
                   4912:     foreach my $grade (@gradedata) {
                   4913: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4914: 	my $domain;
                   4915: 	if ($entries{$fields{'domain'}}) {
                   4916: 	    $domain=$entries{$fields{'domain'}};
                   4917: 	} else {
1.257     albertel 4918: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4919: 	}
1.243     albertel 4920: 	$domain=~s/\s//g;
1.41      ng       4921: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4922: 	$username=~s/\s//g;
1.243     albertel 4923: 	if (!$username) {
                   4924: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4925: 	    $id=~s/\s//g;
1.737     raeburn  4926:             if ($id ne '') {
                   4927: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4928: 	        $username=$ids{$id};
                   4929:             } else {
                   4930:                 if ($entries{$fields{'clicker'}}) {
                   4931:                     my $clicker = $entries{$fields{'clicker'}};
                   4932:                     $clicker=~s/\s//g;
                   4933:                     if ($clicker ne '') {
                   4934:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4935:                         if ($clickers{$clicker} ne '') {  
                   4936:                             my $match = 0;
                   4937:                             my @inclass;
                   4938:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4939:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4940:                                     $username = $poss;
                   4941:                                     push(@inclass,$poss);
                   4942:                                     $match ++;
                   4943:                                     
                   4944:                                 }
                   4945:                             }
                   4946:                             if ($match > 1) {
                   4947:                                 undef($username); 
                   4948:                                 $request->print('<p class="LC_warning">'.
                   4949:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4950:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4951:                             }
                   4952:                         }
                   4953:                     }
                   4954:                 }
                   4955:             }
1.243     albertel 4956: 	}
1.41      ng       4957: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4958: 	    my $id=$entries{$fields{'ID'}};
                   4959: 	    $id=~s/\s//g;
1.737     raeburn  4960:             my $clicker = $entries{$fields{'clicker'}};
                   4961:             $clicker=~s/\s//g;
                   4962:             if ($clicker) {
                   4963:                 push(@skipped,"$clicker:$domain");
                   4964: 	    } elsif ($id) {
1.247     albertel 4965: 		push(@skipped,"$id:$domain");
                   4966: 	    } else {
                   4967: 		push(@skipped,"$username:$domain");
                   4968: 	    }
1.41      ng       4969: 	    next;
                   4970: 	}
1.108     albertel 4971: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4972: 	if (!&canmodify($usec)) {
                   4973: 	    push(@notallowed,"$username:$domain");
                   4974: 	    next;
                   4975: 	}
1.244     albertel 4976: 	my %points;
1.41      ng       4977: 	my %grades;
                   4978: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4979: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4980: 		$dest eq 'domain') { next; }
                   4981: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4982: 	    if ($dest=~/stores_(.*)_points/) {
                   4983: 		my $part=$1;
                   4984: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4985: 					      $symb,$domain,$username);
1.345     bowersj2 4986:                 if ($wgt) {
                   4987:                     $entries{$fields{$dest}}=~s/\s//g;
                   4988:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4989:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4990:                                           : 'correct_by_override';
1.638     www      4991:                     if ($pcr>1) {
1.657     raeburn  4992:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4993:                     }
1.345     bowersj2 4994:                     $grades{"resource.$part.awarded"}=$pcr;
                   4995:                     $grades{"resource.$part.solved"}=$award;
                   4996:                     $points{$part}=1;
                   4997:                 } else {
                   4998:                     $error_msg = "<br />" .
                   4999:                         &mt("Some point values were assigned"
                   5000:                             ." for problems with a weight "
                   5001:                             ."of zero. These values were "
                   5002:                             ."ignored.");
                   5003:                 }
1.244     albertel 5004: 	    } else {
                   5005: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5006: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5007: 		my $store_key=$dest;
                   5008: 		$store_key=~s/^stores/resource/;
                   5009: 		$store_key=~s/_/\./g;
                   5010: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5011: 	    }
1.41      ng       5012: 	}
1.766     raeburn  5013: 	if (! %grades) {
1.508     www      5014:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5015:         } else {
                   5016: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5017: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5018: 					   $env{'request.course.id'},
                   5019: 					   $domain,$username);
1.508     www      5020: 	   if ($result eq 'ok') {
1.627     www      5021: # Successfully stored
1.508     www      5022: 	      $request->print('.');
1.627     www      5023: # Remove from grading queue
                   5024:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5025:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5026:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5027:                                              $domain,$username);
                   5028:               $countdone++;
                   5029:            } else {
1.508     www      5030: 	      $request->print("<p><span class=\"LC_error\">".
                   5031:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5032:                                   "$username:$domain",$result)."</span></p>");
                   5033: 	   }
                   5034: 	   $request->rflush();
                   5035:         }
1.41      ng       5036:     }
1.570     www      5037:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5038:     if (@warnings) {
                   5039:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5040:         $request->print(join(', ',@warnings));
                   5041:     }
1.41      ng       5042:     if (@skipped) {
1.571     www      5043: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5044:         $request->print(join(', ',@skipped));
1.106     albertel 5045:     }
                   5046:     if (@notallowed) {
1.571     www      5047: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5048: 	$request->print(join(', ',@notallowed));
1.41      ng       5049:     }
1.106     albertel 5050:     $request->print("<br />\n");
1.345     bowersj2 5051:     return $error_msg;
1.26      albertel 5052: }
1.44      ng       5053: #------------- end of section for handling csv file upload ---------
                   5054: #
                   5055: #-------------------------------------------------------------------
                   5056: #
1.122     ng       5057: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5058: #
                   5059: #--- Select a page/sequence and a student to grade
1.68      ng       5060: sub pickStudentPage {
1.608     www      5061:     my ($request,$symb) = @_;
1.68      ng       5062: 
1.539     riegler  5063:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5064:     &js_escape(\$alertmsg);
1.597     wenzelju 5065:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5066: 
                   5067: function checkPickOne(formname) {
1.76      ng       5068:     if (radioSelection(formname.student) == null) {
1.539     riegler  5069: 	alert("$alertmsg");
1.68      ng       5070: 	return;
                   5071:     }
1.125     ng       5072:     ptr = pullDownSelection(formname.selectpage);
                   5073:     formname.page.value = formname["page"+ptr].value;
                   5074:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5075:     formname.submit();
                   5076: }
                   5077: 
                   5078: LISTJAVASCRIPT
1.118     ng       5079:     &commonJSfunctions($request);
1.608     www      5080: 
1.257     albertel 5081:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5082:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5083:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5084:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5085: 
1.398     albertel 5086:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5087: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5088: 
1.80      ng       5089:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5090:     my $map_error;
                   5091:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5092:     if ($map_error) {
                   5093:         $request->print(&navmap_errormsg());
                   5094:         return; 
                   5095:     }
1.137     albertel 5096:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5097: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5098: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5099: 
                   5100:     # Collection of hidden fields
1.70      ng       5101:     my $ctr=0;
1.68      ng       5102:     foreach (@$titles) {
1.700     bisitz   5103:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5104:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5105:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5106:         $ctr++;
1.68      ng       5107:     }
1.700     bisitz   5108:     $result.='<input type="hidden" name="page" />'."\n".
                   5109:         '<input type="hidden" name="title" />'."\n";
                   5110: 
                   5111:     $result.=&build_section_inputs();
                   5112:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5113:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5114: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5115: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5116: 
1.700     bisitz   5117:     # Show grading options
                   5118:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5119:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5120:     $ctr=0;
                   5121:     foreach (@$titles) {
                   5122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5123: 	$select.='<option value="'.$ctr.'"'.
                   5124: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5125: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5126: 	$ctr++;
                   5127:     }
1.700     bisitz   5128:     $select.= '</select>';
1.68      ng       5129: 
1.700     bisitz   5130:     $result.=
                   5131:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5132:        .$select
                   5133:        .&Apache::lonhtmlcommon::row_closure();
                   5134: 
                   5135:     $result.=
                   5136:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5137:        .'<label><input type="radio" name="vProb" value="no"'
                   5138:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5139:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5140:            .&mt('yes').'</label>'."\n"
                   5141:        .&Apache::lonhtmlcommon::row_closure();
                   5142: 
                   5143:     $result.=
                   5144:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5145:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5146:            .&mt('none').' </label>'."\n"
                   5147:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5148:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5149:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5150:            .&mt('all submissions with details').' </label>'
                   5151:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5152:     
1.700     bisitz   5153:     $result.=
                   5154:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5155:        .'<input type="text" name="CODE" value="" />'
                   5156:        .&Apache::lonhtmlcommon::row_closure(1)
                   5157:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5158: 
1.700     bisitz   5159:     # Show list of students to select for grading
                   5160:     $result.='<br /><input type="button" '.
1.589     bisitz   5161:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5162: 
1.68      ng       5163:     $request->print($result);
                   5164: 
1.485     albertel 5165:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5166: 	&Apache::loncommon::start_data_table().
                   5167: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5168: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5169: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5170: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5171: 	'<th>'.&nameUserString('header').'</th>'.
                   5172: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5173:  
1.761     raeburn  5174:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5175:     my $ptr = 1;
1.294     albertel 5176:     foreach my $student (sort 
                   5177: 			 {
                   5178: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5179: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5180: 			     }
                   5181: 			     return $a cmp $b;
                   5182: 			 } (keys(%$fullname))) {
1.68      ng       5183: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5184: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5185:                                   : '</td>');
1.126     ng       5186: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5187: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5188: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5189: 	$studentTable.=
                   5190: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5191:                          : '');
1.68      ng       5192: 	$ptr++;
                   5193:     }
1.484     albertel 5194:     if ($ptr%2 == 0) {
                   5195: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5196: 	    &Apache::loncommon::end_data_table_row();
                   5197:     }
                   5198:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5199:     $studentTable.='<input type="button" '.
1.589     bisitz   5200:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5201: 
                   5202:     $request->print($studentTable);
                   5203: 
                   5204:     return '';
                   5205: }
                   5206: 
                   5207: sub getSymbMap {
1.582     raeburn  5208:     my ($map_error) = @_;
1.132     bowersj2 5209:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5210:     unless (ref($navmap)) {
                   5211:         if (ref($map_error)) {
                   5212:             $$map_error = 'navmap';
                   5213:         }
                   5214:         return;
                   5215:     }
1.68      ng       5216:     my %symbx = ();
                   5217:     my @titles = ();
1.117     bowersj2 5218:     my $minder = 0;
                   5219: 
                   5220:     # Gather every sequence that has problems.
1.240     albertel 5221:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5222: 					       1,0,1);
1.117     bowersj2 5223:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5224: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5225: 	    my $title = $minder.'.'.
                   5226: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5227: 	    push(@titles, $title); # minder in case two titles are identical
                   5228: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5229: 	    $minder++;
1.241     albertel 5230: 	}
1.68      ng       5231:     }
                   5232:     return \@titles,\%symbx;
                   5233: }
                   5234: 
1.72      ng       5235: #
                   5236: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5237: sub displayPage {
1.608     www      5238:     my ($request,$symb) = @_;
1.257     albertel 5239:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5240:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5241:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5242:     my $pageTitle = $env{'form.page'};
1.103     albertel 5243:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5244:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5245:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5246: 
                   5247:     #need to make sure we have the correct data for later EXT calls, 
                   5248:     #thus invalidate the cache
                   5249:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5250:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5251:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5252:     &Apache::lonnet::clear_EXT_cache_status();
                   5253: 
1.103     albertel 5254:     if (!&canview($usec)) {
1.712     bisitz   5255:         $request->print(
                   5256:             '<span class="LC_warning">'.
                   5257:             &mt('Unable to view requested student. ([_1])',
                   5258:                     $env{'form.student'}).
                   5259:             '</span>');
                   5260:         return;
1.103     albertel 5261:     }
1.398     albertel 5262:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5263:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5264: 	'</h3>'."\n";
1.500     albertel 5265:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5266:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5267: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5268:     } else {
                   5269: 	delete($env{'form.CODE'});
                   5270:     }
1.71      ng       5271:     &sub_page_js($request);
                   5272:     $request->print($result);
                   5273: 
1.132     bowersj2 5274:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5275:     unless (ref($navmap)) {
                   5276:         $request->print(&navmap_errormsg());
                   5277:         return;
                   5278:     }
1.257     albertel 5279:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5280:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5281:     if (!$map) {
1.485     albertel 5282: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5283: 	return; 
                   5284:     }
1.68      ng       5285:     my $iterator = $navmap->getIterator($map->map_start(),
                   5286: 					$map->map_finish());
                   5287: 
1.71      ng       5288:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5289: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5290: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5291: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5292: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5293: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5294: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5295: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5296: 
1.382     albertel 5297:     if (defined($env{'form.CODE'})) {
                   5298: 	$studentTable.=
                   5299: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5300:     }
1.381     albertel 5301:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5302: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5303: 
1.594     bisitz   5304:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5305:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5306:         '</span>'."\n".
1.484     albertel 5307: 	&Apache::loncommon::start_data_table().
                   5308: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5309: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5310: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5311: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5312: 
1.329     albertel 5313:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5314:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5315:     $iterator->next(); # skip the first BEGIN_MAP
                   5316:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5317:     while ($depth > 0) {
1.68      ng       5318:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5319:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5320: 
1.745     raeburn  5321:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5322: 	    my $parts = $curRes->parts();
1.68      ng       5323:             my $title = $curRes->compTitle();
1.71      ng       5324: 	    my $symbx = $curRes->symb();
1.746     raeburn  5325:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5326: 	    $studentTable.=
                   5327: 		&Apache::loncommon::start_data_table_row().
                   5328: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5329: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5330: 		                        : '<br />('.&mt('[_1]parts',
                   5331: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5332: 		 ).
                   5333: 		 '</td>';
1.71      ng       5334: 	    $studentTable.='<td valign="top">';
1.382     albertel 5335: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5336:             if ($is_tool) {
                   5337:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5338:             } else {
1.745     raeburn  5339: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5340: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5341: 					         undef,'both',\%form);
                   5342: 	        } else {
                   5343: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5344: 		    $companswer =~ s|<form(.*?)>||g;
                   5345: 		    $companswer =~ s|</form>||g;
                   5346: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5347: #		        $companswer =~ s/$1/ /ms;
                   5348: #		        $request->print('match='.$1."<br />\n");
                   5349: #		    }
                   5350: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5351: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5352: 		}
1.71      ng       5353: 	    }
                   5354: 
1.257     albertel 5355: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5356: 
1.257     albertel 5357: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5358: 		if ($record{'version'} eq '') {
1.745     raeburn  5359:                     my $msg = &mt('No recorded submission for this problem.');
                   5360:                     if ($is_tool) {
                   5361:                         $msg = &mt('No recorded transactions for this external tool');
                   5362:                     }
                   5363: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5364: 		} else {
1.116     ng       5365: 		    my %responseType = ();
                   5366: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5367: 			my @responseIds =$curRes->responseIds($partid);
                   5368: 			my @responseType =$curRes->responseType($partid);
                   5369: 			my %responseIds;
                   5370: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5371: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5372: 			}
                   5373: 			$responseType{$partid} = \%responseIds;
1.116     ng       5374: 		    }
1.148     albertel 5375: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5376: 		}
1.257     albertel 5377: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5378: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5379:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5380: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5381: 									$env{'request.course.id'},
1.726     raeburn  5382: 									'','.submission',undef,
                   5383:                                                                         $usec,$identifier);
1.71      ng       5384:  
                   5385: 	    }
1.103     albertel 5386: 	    if (&canmodify($usec)) {
1.585     bisitz   5387:             $studentTable.=&gradeBox_start();
1.103     albertel 5388: 		foreach my $partid (@{$parts}) {
                   5389: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5390: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5391: 		    $question++;
                   5392: 		}
1.585     bisitz   5393:             $studentTable.=&gradeBox_end();
1.196     albertel 5394: 		$prob++;
1.71      ng       5395: 	    }
                   5396: 	    $studentTable.='</td></tr>';
1.68      ng       5397: 
1.103     albertel 5398: 	}
1.68      ng       5399:         $curRes = $iterator->next();
                   5400:     }
                   5401: 
1.589     bisitz   5402:     $studentTable.=
                   5403:         '</table>'."\n".
                   5404:         '<input type="button" value="'.&mt('Save').'" '.
                   5405:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5406:         '</form>'."\n";
1.71      ng       5407:     $request->print($studentTable);
                   5408: 
                   5409:     return '';
1.119     ng       5410: }
                   5411: 
                   5412: sub displaySubByDates {
1.148     albertel 5413:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5414:     my $isCODE=0;
1.335     albertel 5415:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5416:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5417:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5418:     my $studentTable=&Apache::loncommon::start_data_table().
                   5419: 	&Apache::loncommon::start_data_table_header_row().
                   5420: 	'<th>'.&mt('Date/Time').'</th>'.
                   5421: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5422:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5423: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5424: 	'<th>'.&mt('Status').'</th>'.
                   5425: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5426:     my ($version);
                   5427:     my %mark;
1.148     albertel 5428:     my %orders;
1.119     ng       5429:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5430:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5431:         if ($is_tool) {
                   5432:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5433:         } else {
                   5434:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5435:         }
1.147     albertel 5436:     }
1.335     albertel 5437: 
                   5438:     my $interaction;
1.525     raeburn  5439:     my $no_increment = 1;
1.735     raeburn  5440:     my (%lastrndseed,%lasttype);
1.119     ng       5441:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5442: 	my $timestamp = 
                   5443: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5444: 	if (exists($$record{$version.':resource.0.version'})) {
                   5445: 	    $interaction = $$record{$version.':resource.0.version'};
                   5446: 	}
1.671     raeburn  5447:         if ($isTask && $env{'form.previousversion'}) {
                   5448:             next unless ($interaction == $env{'form.previousversion'});
                   5449:         }
1.335     albertel 5450: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5451: 		             : "$version:resource");
1.467     albertel 5452: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5453: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5454: 	if ($isCODE) {
                   5455: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5456: 	}
1.671     raeburn  5457:         if ($isTask) {
                   5458:             $studentTable.='<td>'.$interaction.'</td>';
                   5459:         }
1.119     ng       5460: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5461: 	my @displaySub = ();
                   5462: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5463:             my ($hidden,$type);
                   5464:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5465:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5466:                 $hidden = 1;
                   5467:             }
1.749     raeburn  5468:             my @matchKey;
                   5469:             if ($isTask) {
1.769     raeburn  5470:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5471:             } elsif ($is_tool) {
1.769     raeburn  5472:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5473:             } else {
1.769     raeburn  5474:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5475:             }
1.122     ng       5476: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5477: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5478: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5479: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5480: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5481:                     if ($is_tool) {
                   5482:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5483:                     } else {
1.749     raeburn  5484: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5485: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5486:                         $displaySub[0].='<span class="LC_nobreak">';
                   5487:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5488:                                        .' <span class="LC_internal_info">'
                   5489:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5490:                                        .'</span>'
                   5491:                                        .' <b>';
                   5492:                         if ($hidden) {
                   5493:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5494:                         } else {
                   5495:                             my ($trial,$rndseed,$newvariation);
                   5496:                             if ($type eq 'randomizetry') {
                   5497:                                 $trial = $$record{"$where.$partid.tries"};
                   5498:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5499:                             }
                   5500: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5501: 			        $displaySub[0].=&mt('Trial not counted');
                   5502: 		            } else {
                   5503: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5504: 					        $$record{"$where.$partid.tries"});
                   5505:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5506:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5507:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5508:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5509:                                     }
1.640     raeburn  5510:                                 }
1.749     raeburn  5511:                                 $lastrndseed{$partid} = $rndseed;
                   5512:                                 $lasttype{$partid} = $type;
                   5513: 		            }
                   5514: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5515:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5516: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5517: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5518: 			        $orders{$partid}->{$responseId}=
                   5519: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5520:                                                $no_increment,$type,$trial,$rndseed);
                   5521: 		            }
                   5522: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5523: 		            $displaySub[0].='&nbsp; '.
                   5524: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5525:                         }
1.596     raeburn  5526:                     }
1.147     albertel 5527: 		}
                   5528: 	    }
1.335     albertel 5529: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5530: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5531: 				    $$record{"$where.$partid.checkedin"},
                   5532: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5533: 					'<br />';
1.335     albertel 5534: 	    }
                   5535: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5536: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5537: 		    lc($$record{"$where.$partid.award"}).' '.
                   5538: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5539: 		    '<br />';
1.749     raeburn  5540: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5541: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5542: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5543: 		}
1.147     albertel 5544: 	    }
1.335     albertel 5545: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5546: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5547: 		unless ($is_tool) {
                   5548: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5549: 		}
1.335     albertel 5550: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5551: 		$displaySub[2].=
1.749     raeburn  5552: 		    $$record{"$version:resource.$partid.regrader"};
                   5553:                 unless ($is_tool) {
                   5554: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5555:                 }
1.147     albertel 5556: 	    }
                   5557: 	}
                   5558: 	# needed because old essay regrader has not parts info
                   5559: 	if (exists $$record{"$version:resource.regrader"}) {
                   5560: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5561: 	}
                   5562: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5563: 	if ($displaySub[2]) {
1.467     albertel 5564: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5565: 	}
1.467     albertel 5566: 	$studentTable.='&nbsp;</td>'.
                   5567: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5568:     }
1.467     albertel 5569:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5570:     return $studentTable;
1.71      ng       5571: }
                   5572: 
                   5573: sub updateGradeByPage {
1.608     www      5574:     my ($request,$symb) = @_;
1.71      ng       5575: 
1.257     albertel 5576:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5577:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5578:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5579:     my $pageTitle = $env{'form.page'};
1.103     albertel 5580:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5581:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5582:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5583:     if (!&canmodify($usec)) {
1.526     raeburn  5584: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5585: 	return;
                   5586:     }
1.398     albertel 5587:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5588:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5589: 	'</h3>'."\n";
1.70      ng       5590: 
1.68      ng       5591:     $request->print($result);
                   5592: 
1.582     raeburn  5593: 
1.132     bowersj2 5594:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5595:     unless (ref($navmap)) {
                   5596:         $request->print(&navmap_errormsg());
                   5597:         return;
                   5598:     }
1.257     albertel 5599:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5600:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5601:     if (!$map) {
1.527     raeburn  5602: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5603: 	return; 
                   5604:     }
1.71      ng       5605:     my $iterator = $navmap->getIterator($map->map_start(),
                   5606: 					$map->map_finish());
1.70      ng       5607: 
1.484     albertel 5608:     my $studentTable=
                   5609: 	&Apache::loncommon::start_data_table().
                   5610: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5611: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5612: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5613: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5614: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5615: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5616: 
                   5617:     $iterator->next(); # skip the first BEGIN_MAP
                   5618:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5619:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5620:     while ($depth > 0) {
1.71      ng       5621:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5622:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5623: 
1.385     albertel 5624:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5625: 	    my $parts = $curRes->parts();
1.71      ng       5626:             my $title = $curRes->compTitle();
                   5627: 	    my $symbx = $curRes->symb();
1.484     albertel 5628: 	    $studentTable.=
                   5629: 		&Apache::loncommon::start_data_table_row().
                   5630: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5631: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5632:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5633: 		.')').'</td>';
1.71      ng       5634: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5635: 
                   5636: 	    my %newrecord=();
                   5637: 	    my @displayPts=();
1.269     raeburn  5638:             my %aggregate = ();
                   5639:             my $aggregateflag = 0;
1.726     raeburn  5640:             if ($env{'form.HIDE'.$prob}) {
                   5641:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5642:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5643:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5644:                 $hideflag += $numchgs;
                   5645:             }
1.71      ng       5646: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5647: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5648: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5649: 
1.257     albertel 5650: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5651: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5652: 		my $partial = $newpts/$wgt;
                   5653: 		my $score;
                   5654: 		if ($partial > 0) {
                   5655: 		    $score = 'correct_by_override';
1.125     ng       5656: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5657: 		    $score = 'incorrect_by_override';
                   5658: 		}
1.257     albertel 5659: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5660: 		if ($dropMenu eq 'excused') {
1.71      ng       5661: 		    $partial = '';
                   5662: 		    $score = 'excused';
1.125     ng       5663: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5664: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5665: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5666: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5667: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5668: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5669: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5670: 		    $changeflag++;
                   5671: 		    $newpts = '';
1.269     raeburn  5672:                     
                   5673:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5674:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5675:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5676:                     if ($aggtries > 0) {
                   5677:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5678:                         $aggregateflag = 1;
                   5679:                     }
1.71      ng       5680: 		}
1.324     albertel 5681: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5682: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5683: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5684: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5685: 		    '&nbsp;<br />';
1.526     raeburn  5686: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5687: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5688: 		    '&nbsp;<br />';
1.71      ng       5689: 		$question++;
1.380     albertel 5690: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5691: 
1.71      ng       5692: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5693: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5694: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5695: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5696: 
                   5697: 		$changeflag++;
                   5698: 	    }
                   5699: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5700: 		my %record = 
                   5701: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5702: 					     $udom,$uname);
                   5703: 
                   5704: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5705: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5706: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5707: 		    $newrecord{'resource.CODE'} = '';
                   5708: 		}
1.257     albertel 5709: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5710: 					$udom,$uname);
1.382     albertel 5711: 		%record = &Apache::lonnet::restore($symbx,
                   5712: 						   $env{'request.course.id'},
                   5713: 						   $udom,$uname);
1.380     albertel 5714: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5715: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5716: 	    }
1.380     albertel 5717: 	    
1.269     raeburn  5718:             if ($aggregateflag) {
                   5719:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5720:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5721:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5722:             }
1.125     ng       5723: 
1.71      ng       5724: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5725: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5726: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5727: 
1.196     albertel 5728: 	    $prob++;
1.68      ng       5729: 	}
1.71      ng       5730:         $curRes = $iterator->next();
1.68      ng       5731:     }
1.98      albertel 5732: 
1.484     albertel 5733:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5734:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5735: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5736: 		  $changeflag).'<br />');
                   5737:     my $hidemsg=($hideflag == 0 ? '' :
                   5738:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5739:                      $hideflag).'<br />');
                   5740:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5741: 
1.70      ng       5742:     return '';
                   5743: }
                   5744: 
1.72      ng       5745: #-------- end of section for handling grading by page/sequence ---------
                   5746: #
                   5747: #-------------------------------------------------------------------
                   5748: 
1.581     www      5749: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5750: #
                   5751: #------ start of section for handling grading by page/sequence ---------
                   5752: 
1.423     albertel 5753: =pod
                   5754: 
                   5755: =head1 Bubble sheet grading routines
                   5756: 
1.424     albertel 5757:   For this documentation:
                   5758: 
                   5759:    'scanline' refers to the full line of characters
                   5760:    from the file that we are parsing that represents one entire sheet
                   5761: 
                   5762:    'bubble line' refers to the data
1.659     raeburn  5763:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5764: 
                   5765: 
1.659     raeburn  5766: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5767: into a course. When a user wants to grade, they select a
1.659     raeburn  5768: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5769: one of the predefined configurations for what each scanline looks
                   5770: like.
                   5771: 
                   5772: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5773: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5774: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5775: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5776: invalid student/employee ID
1.424     albertel 5777: 
                   5778: If the CODE option is used that determines the randomization of the
1.556     weissno  5779: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5780: username:domain.
                   5781: 
                   5782: During the validation phase the instructor can choose to skip scanlines. 
                   5783: 
1.659     raeburn  5784: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5785: 
                   5786:   scantron_original_filename (unmodified original file)
                   5787:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5788:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5789: 
                   5790: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5791: correction information that isn't representable in the bubblesheet
1.424     albertel 5792: file (see &scantron_getfile() for more information)
                   5793: 
                   5794: After all scanlines are either valid, marked as valid or skipped, then
                   5795: foreach line foreach problem in the picked sequence, an ssi request is
                   5796: made that simulates a user submitting their selected letter(s) against
                   5797: the homework problem.
1.423     albertel 5798: 
                   5799: =over 4
                   5800: 
                   5801: 
                   5802: 
                   5803: =item defaultFormData
                   5804: 
                   5805:   Returns html hidden inputs used to hold context/default values.
                   5806: 
                   5807:  Arguments:
                   5808:   $symb - $symb of the current resource 
                   5809: 
                   5810: =cut
1.422     foxr     5811: 
1.81      albertel 5812: sub defaultFormData {
1.324     albertel 5813:     my ($symb)=@_;
1.766     raeburn  5814:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5815: }
                   5816: 
1.447     foxr     5817: 
1.423     albertel 5818: =pod 
                   5819: 
                   5820: =item getSequenceDropDown
                   5821: 
                   5822:    Return html dropdown of possible sequences to grade
                   5823:  
                   5824:  Arguments:
1.582     raeburn  5825:    $symb - $symb of the current resource
                   5826:    $map_error - ref to scalar which will container error if
                   5827:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5828: 
                   5829: =cut
1.422     foxr     5830: 
1.75      albertel 5831: sub getSequenceDropDown {
1.582     raeburn  5832:     my ($symb,$map_error)=@_;
1.75      albertel 5833:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5834:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5835:     if (ref($map_error)) {
                   5836:         return if ($$map_error);
                   5837:     }
1.137     albertel 5838:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5839:     my $ctr=0;
                   5840:     foreach (@$titles) {
                   5841: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5842: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5843: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5844: 	    '>'.$showtitle.'</option>'."\n";
                   5845: 	$ctr++;
                   5846:     }
                   5847:     $result.= '</select>';
                   5848:     return $result;
                   5849: }
                   5850: 
1.495     albertel 5851: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5852:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5853: 
                   5854: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5855: 
1.509     raeburn  5856: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5857:                                    # matchresponse or rankresponse, where 
                   5858:                                    # an individual response can have multiple 
                   5859:                                    # lines
1.503     raeburn  5860: 
                   5861: my %responsetype_per_response;     # responsetype for each response
                   5862: 
1.691     raeburn  5863: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5864:                                    # numbered response. Needed when randomorder
                   5865:                                    # or randompick are in use. Key is ID, value 
                   5866:                                    # is response number.
                   5867: 
1.495     albertel 5868: # Save and restore the bubble lines array to the form env.
                   5869: 
                   5870: 
                   5871: sub save_bubble_lines {
                   5872:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5873: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5874: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5875: 	    $first_bubble_line{$line};
1.503     raeburn  5876:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5877:             $subdivided_bubble_lines{$line};
                   5878:         $env{"form.scantron.responsetype.$line"} =
                   5879:             $responsetype_per_response{$line};
1.495     albertel 5880:     }
1.691     raeburn  5881:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5882:         my $line = $masterseq_id_responsenum{$resid};
                   5883:         $env{"form.scantron.residpart.$line"} = $resid;
                   5884:     }
1.495     albertel 5885: }
                   5886: 
                   5887: 
                   5888: sub restore_bubble_lines {
                   5889:     my $line = 0;
                   5890:     %bubble_lines_per_response = ();
1.691     raeburn  5891:     %masterseq_id_responsenum = ();
1.495     albertel 5892:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5893: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5894: 	$bubble_lines_per_response{$line} = $value;
                   5895: 	$first_bubble_line{$line}  =
                   5896: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5897:         $subdivided_bubble_lines{$line} =
                   5898:             $env{"form.scantron.sub_bubblelines.$line"};
                   5899:         $responsetype_per_response{$line} =
                   5900:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5901:         my $id = $env{"form.scantron.residpart.$line"};
                   5902:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5903: 	$line++;
                   5904:     }
                   5905: }
                   5906: 
1.423     albertel 5907: =pod 
                   5908: 
                   5909: =item scantron_filenames
                   5910: 
                   5911:    Returns a list of the scantron files in the current course 
                   5912: 
                   5913: =cut
1.422     foxr     5914: 
1.202     albertel 5915: sub scantron_filenames {
1.257     albertel 5916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5917:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5918:     my $getpropath = 1;
1.662     raeburn  5919:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5920:                                                         $cname,$getpropath);
1.202     albertel 5921:     my @possiblenames;
1.662     raeburn  5922:     if (ref($dirlist) eq 'ARRAY') {
                   5923:         foreach my $filename (sort(@{$dirlist})) {
                   5924: 	    ($filename)=split(/&/,$filename);
                   5925: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5926: 	    $filename=~s/^scantron_orig_//;
                   5927: 	    push(@possiblenames,$filename);
                   5928:         }
1.202     albertel 5929:     }
                   5930:     return @possiblenames;
                   5931: }
                   5932: 
1.423     albertel 5933: =pod 
                   5934: 
                   5935: =item scantron_uploads
                   5936: 
                   5937:    Returns  html drop-down list of scantron files in current course.
                   5938: 
                   5939:  Arguments:
                   5940:    $file2grade - filename to set as selected in the dropdown
                   5941: 
                   5942: =cut
1.422     foxr     5943: 
1.202     albertel 5944: sub scantron_uploads {
1.209     ng       5945:     my ($file2grade) = @_;
1.202     albertel 5946:     my $result=	'<select name="scantron_selectfile">';
                   5947:     $result.="<option></option>";
                   5948:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5949: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5950:     }
                   5951:     $result.="</select>";
                   5952:     return $result;
                   5953: }
                   5954: 
1.423     albertel 5955: =pod 
                   5956: 
                   5957: =item scantron_scantab
                   5958: 
                   5959:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5960:   file.
                   5961: 
                   5962: =cut
1.422     foxr     5963: 
1.82      albertel 5964: sub scantron_scantab {
                   5965:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5966:     $result.='<option></option>'."\n";
1.754     raeburn  5967:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5968:     if (@lines > 0) {
                   5969:         foreach my $line (@lines) {
                   5970:             next if (($line =~ /^\#/) || ($line eq ''));
                   5971: 	    my ($name,$descrip)=split(/:/,$line);
                   5972: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5973:         }
1.82      albertel 5974:     }
                   5975:     $result.='</select>'."\n";
1.518     raeburn  5976:     return $result;
                   5977: }
                   5978: 
1.423     albertel 5979: =pod 
                   5980: 
                   5981: =item scantron_CODElist
                   5982: 
                   5983:   Returns html drop down of the saved CODE lists from current course,
                   5984:   generated from earlier printings.
                   5985: 
                   5986: =cut
1.422     foxr     5987: 
1.186     albertel 5988: sub scantron_CODElist {
1.257     albertel 5989:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5990:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5991:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5992:     my $namechoice='<option></option>';
1.225     albertel 5993:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5994: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5995: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5996: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5997:     }
                   5998:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5999:     return $namechoice;
                   6000: }
                   6001: 
1.423     albertel 6002: =pod 
                   6003: 
                   6004: =item scantron_CODEunique
                   6005: 
                   6006:   Returns the html for "Each CODE to be used once" radio.
                   6007: 
                   6008: =cut
1.422     foxr     6009: 
1.186     albertel 6010: sub scantron_CODEunique {
1.532     bisitz   6011:     my $result='<span class="LC_nobreak">
1.272     albertel 6012:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6013:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6014:                 </span>
1.532     bisitz   6015:                 <span class="LC_nobreak">
1.272     albertel 6016:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6017:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6018:                 </span>';
1.186     albertel 6019:     return $result;
                   6020: }
1.423     albertel 6021: 
                   6022: =pod 
                   6023: 
                   6024: =item scantron_selectphase
                   6025: 
1.659     raeburn  6026:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6027:   Allows for - starting a grading run.
1.424     albertel 6028:              - downloading existing scan data (original, corrected
1.423     albertel 6029:                                                 or skipped info)
                   6030: 
                   6031:              - uploading new scan data
                   6032: 
                   6033:  Arguments:
                   6034:   $r          - The Apache request object
                   6035:   $file2grade - name of the file that contain the scanned data to score
                   6036: 
                   6037: =cut
1.186     albertel 6038: 
1.75      albertel 6039: sub scantron_selectphase {
1.608     www      6040:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6041:     if (!$symb) {return '';}
1.582     raeburn  6042:     my $map_error;
                   6043:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6044:     if ($map_error) {
                   6045:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6046:         return;
                   6047:     }
1.324     albertel 6048:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6049:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6050:     my $format_selector=&scantron_scantab();
1.186     albertel 6051:     my $CODE_selector=&scantron_CODElist();
                   6052:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6053:     my $result;
1.422     foxr     6054: 
1.513     foxr     6055:     $ssi_error = 0;
                   6056: 
1.770     raeburn  6057:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6058: 
                   6059: 	# Chunk of form to prompt for a scantron file upload.
                   6060: 
                   6061:         $r->print('
1.754     raeburn  6062:     <br />');
1.606     wenzelju 6063:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6064:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6065:     my $csec= $env{'request.course.sec'};
1.736     damieng  6066:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6067:     &js_escape(\$alertmsg);
1.754     raeburn  6068:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6069:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6070:     function checkUpload(formname) {
                   6071: 	if (formname.upfile.value == "") {
1.736     damieng  6072: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6073: 	    return false;
                   6074: 	}
                   6075: 	formname.submit();
1.756     raeburn  6076:     }'."\n".$formatjs));
1.606     wenzelju 6077:     $r->print('
                   6078:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6079:                 '.$default_form_data.'
                   6080:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6081:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6082:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6083:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6084:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6085:               '.&Apache::loncommon::start_data_table_header_row().'
                   6086:                 <th>
                   6087:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6088:                 </th>
                   6089:               '.&Apache::loncommon::end_data_table_header_row().'
                   6090:               '.&Apache::loncommon::start_data_table_row().'
                   6091:             <td>
                   6092:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6093:     if ($formatoptions) {
                   6094:         $r->print('</td>
                   6095:                  '.&Apache::loncommon::end_data_table_row().'
                   6096:                  '.&Apache::loncommon::start_data_table_row().'
                   6097:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6098:                  </td>
                   6099:                  '.&Apache::loncommon::end_data_table_row().'
                   6100:                  '.&Apache::loncommon::start_data_table_row().'
                   6101:                  <td>'
                   6102:         );
                   6103:     } else {
                   6104:         $r->print(' <br />');
                   6105:     }
                   6106:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6107:               </td>
                   6108:              '.&Apache::loncommon::end_data_table_row().'
                   6109:              '.&Apache::loncommon::end_data_table().'
                   6110:              </form>'
                   6111:     );
1.606     wenzelju 6112: 
                   6113:     }
                   6114: 
1.422     foxr     6115:     # Chunk of form to prompt for a file to grade and how:
                   6116: 
1.489     albertel 6117:     $result.= '
                   6118:     <br />
                   6119:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6120:     <input type="hidden" name="command" value="scantron_warning" />
                   6121:     '.$default_form_data.'
                   6122:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6123:        '.&Apache::loncommon::start_data_table_header_row().'
                   6124:             <th colspan="2">
1.492     albertel 6125:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6126:             </th>
                   6127:        '.&Apache::loncommon::end_data_table_header_row().'
                   6128:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6129:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6130:        '.&Apache::loncommon::end_data_table_row().'
                   6131:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6132:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6133:        '.&Apache::loncommon::end_data_table_row().'
                   6134:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6135:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6136:        '.&Apache::loncommon::end_data_table_row().'
                   6137:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6138:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6139:        '.&Apache::loncommon::end_data_table_row().'
                   6140:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6141:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6142:        '.&Apache::loncommon::end_data_table_row().'
                   6143:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6144: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6145:             <td>
1.492     albertel 6146: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6147:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6148:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6149: 	    </td>
1.489     albertel 6150:        '.&Apache::loncommon::end_data_table_row().'
                   6151:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6152:             <td colspan="2">
1.572     www      6153:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6154:             </td>
1.489     albertel 6155:        '.&Apache::loncommon::end_data_table_row().'
                   6156:     '.&Apache::loncommon::end_data_table().'
                   6157:     </form>
                   6158: ';
1.162     albertel 6159:    
                   6160:     $r->print($result);
                   6161: 
1.422     foxr     6162:     # Chunk of the form that prompts to view a scoring office file,
                   6163:     # corrected file, skipped records in a file.
                   6164: 
1.489     albertel 6165:     $r->print('
                   6166:    <br />
                   6167:    <form action="/adm/grades" name="scantron_download">
                   6168:      '.$default_form_data.'
                   6169:      <input type="hidden" name="command" value="scantron_download" />
                   6170:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6171:        '.&Apache::loncommon::start_data_table_header_row().'
                   6172:               <th>
1.492     albertel 6173:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6174:               </th>
                   6175:        '.&Apache::loncommon::end_data_table_header_row().'
                   6176:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6177:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6178:                 <br />
1.492     albertel 6179:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6180:        '.&Apache::loncommon::end_data_table_row().'
                   6181:      '.&Apache::loncommon::end_data_table().'
                   6182:    </form>
                   6183:    <br />
                   6184: ');
1.162     albertel 6185: 
1.457     banghart 6186:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6187: 
1.694     bisitz   6188:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6189:              $default_form_data."\n".
                   6190:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6191:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6192:              '<th colspan="2">
1.572     www      6193:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6194:              '</th>'."\n".
                   6195:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6196:               &Apache::loncommon::start_data_table_row()."\n".
                   6197:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6198:               '<td> '.$sequence_selector.' </td>'.
                   6199:               &Apache::loncommon::end_data_table_row()."\n".
                   6200:               &Apache::loncommon::start_data_table_row()."\n".
                   6201:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6202:               '<td> '.$file_selector.' </td>'."\n".
                   6203:               &Apache::loncommon::end_data_table_row()."\n".
                   6204:               &Apache::loncommon::start_data_table_row()."\n".
                   6205:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6206:               '<td> '.$format_selector.' </td>'."\n".
                   6207:               &Apache::loncommon::end_data_table_row()."\n".
                   6208:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6209:               '<td> '.&mt('Options').' </td>'."\n".
                   6210:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6211:               &Apache::loncommon::end_data_table_row()."\n".
                   6212:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6213:               '<td colspan="2">'."\n".
                   6214:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6215:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6216:               '</td>'."\n".
                   6217:               &Apache::loncommon::end_data_table_row()."\n".
                   6218:               &Apache::loncommon::end_data_table()."\n".
                   6219:               '</form><br />');
                   6220:     return;
1.75      albertel 6221: }
                   6222: 
1.423     albertel 6223: =pod 
                   6224: 
                   6225: =item username_to_idmap
                   6226: 
1.556     weissno  6227:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6228:     student username:domain. If a single ID occurs for more than one student,
                   6229:     the status of the student is checked, and if Active, the value in the hash
                   6230:     will be set to the Active student.
1.423     albertel 6231: 
                   6232:   Arguments:
                   6233: 
                   6234:     $classlist - reference to the class list hash. This is a hash
                   6235:                  keyed by student name:domain  whose elements are references
1.424     albertel 6236:                  to arrays containing various chunks of information
1.423     albertel 6237:                  about the student. (See loncoursedata for more info).
                   6238: 
                   6239:   Returns
                   6240:     %idmap - the constructed hash
                   6241: 
                   6242: =cut
                   6243: 
1.82      albertel 6244: sub username_to_idmap {
                   6245:     my ($classlist)= @_;
                   6246:     my %idmap;
                   6247:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6248:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6249:         unless ($id eq '') {
                   6250:             if (!exists($idmap{$id})) {
                   6251:                 $idmap{$id} = $student;
                   6252:             } else {
                   6253:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6254:                 if ($status eq 'Active') {
                   6255:                     $idmap{$id} = $student;
                   6256:                 }
                   6257:             }
                   6258:         }
1.82      albertel 6259:     }
                   6260:     return %idmap;
                   6261: }
1.423     albertel 6262: 
                   6263: =pod
                   6264: 
1.424     albertel 6265: =item scantron_fixup_scanline
1.423     albertel 6266: 
                   6267:    Process a requested correction to a scanline.
                   6268: 
                   6269:   Arguments:
1.754     raeburn  6270:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6271:     $scan_data         - hash of correction information 
                   6272:                           (see &scantron_getfile())
                   6273:     $line              - existing scanline
                   6274:     $whichline         - line number of the passed in scanline
                   6275:     $field             - type of change to process 
                   6276:                          (either 
1.573     bisitz   6277:                           'ID'     -> correct the student/employee ID
1.423     albertel 6278:                           'CODE'   -> correct the CODE
                   6279:                           'answer' -> fixup the submitted answers)
                   6280:     
                   6281:    $args               - hash of additional info,
                   6282:                           - 'ID' 
                   6283:                                'newid' -> studentID to use in replacement
1.424     albertel 6284:                                           of existing one
1.423     albertel 6285:                           - 'CODE' 
                   6286:                                'CODE_ignore_dup' - set to true if duplicates
                   6287:                                                    should be ignored.
                   6288: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6289:                                         if the existing unfound code should
1.423     albertel 6290:                                         be used as is
                   6291:                           - 'answer'
                   6292:                                'response' - new answer or 'none' if blank
                   6293:                                'question' - the bubble line to change
1.503     raeburn  6294:                                'questionnum' - the question identifier,
                   6295:                                                may include subquestion. 
1.423     albertel 6296: 
                   6297:   Returns:
                   6298:     $line - the modified scanline
                   6299: 
                   6300:   Side effects: 
                   6301:     $scan_data - may be updated
                   6302: 
                   6303: =cut
                   6304: 
1.82      albertel 6305: 
1.157     albertel 6306: sub scantron_fixup_scanline {
                   6307:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6308:     if ($field eq 'ID') {
                   6309: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6310: 	    return ($line,1,'New value too large');
1.157     albertel 6311: 	}
                   6312: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6313: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6314: 				     $args->{'newid'});
                   6315: 	}
                   6316: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6317: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6318: 	if ($args->{'newid'}=~/^\s*$/) {
                   6319: 	    &scan_data($scan_data,"$whichline.user",
                   6320: 		       $args->{'username'}.':'.$args->{'domain'});
                   6321: 	}
1.186     albertel 6322:     } elsif ($field eq 'CODE') {
1.192     albertel 6323: 	if ($args->{'CODE_ignore_dup'}) {
                   6324: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6325: 	}
                   6326: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6327: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6328: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6329: 		return ($line,1,'New CODE value too large');
                   6330: 	    }
                   6331: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6332: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6333: 	    }
                   6334: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6335: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6336: 	}
1.157     albertel 6337:     } elsif ($field eq 'answer') {
1.497     foxr     6338: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6339: 	my $off=$scantron_config->{'Qoff'};
                   6340: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6341: 	my $answer=${off}x$length;
                   6342: 	if ($args->{'response'} eq 'none') {
                   6343: 	    &scan_data($scan_data,
1.503     raeburn  6344: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6345: 	} else {
                   6346: 	    if ($on eq 'letter') {
                   6347: 		my @alphabet=('A'..'Z');
                   6348: 		$answer=$alphabet[$args->{'response'}];
                   6349: 	    } elsif ($on eq 'number') {
                   6350: 		$answer=$args->{'response'}+1;
                   6351: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6352: 	    } else {
1.497     foxr     6353: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6354: 	    }
1.497     foxr     6355: 	    &scan_data($scan_data,
1.503     raeburn  6356: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6357: 	}
1.497     foxr     6358: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6359: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6360:     }
                   6361:     return $line;
                   6362: }
1.423     albertel 6363: 
                   6364: =pod
                   6365: 
                   6366: =item scan_data
                   6367: 
                   6368:     Edit or look up  an item in the scan_data hash.
                   6369: 
                   6370:   Arguments:
                   6371:     $scan_data  - The hash (see scantron_getfile)
                   6372:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6373:                   scantronfilename_key).
1.423     albertel 6374:     $data        - New value of the hash entry.
                   6375:     $delete      - If true, the entry is removed from the hash.
                   6376: 
                   6377:   Returns:
                   6378:     The new value of the hash table field (undefined if deleted).
                   6379: 
                   6380: =cut
                   6381: 
                   6382: 
1.157     albertel 6383: sub scan_data {
                   6384:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6385:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6386:     if (defined($value)) {
                   6387: 	$scan_data->{$filename.'_'.$key} = $value;
                   6388:     }
                   6389:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6390:     return $scan_data->{$filename.'_'.$key};
                   6391: }
1.423     albertel 6392: 
1.495     albertel 6393: # ----- These first few routines are general use routines.----
                   6394: 
                   6395: # Return the number of occurences of a pattern in a string.
                   6396: 
                   6397: sub occurence_count {
                   6398:     my ($string, $pattern) = @_;
                   6399: 
                   6400:     my @matches = ($string =~ /$pattern/g);
                   6401: 
                   6402:     return scalar(@matches);
                   6403: }
                   6404: 
                   6405: 
                   6406: # Take a string known to have digits and convert all the
                   6407: # digits into letters in the range J,A..I.
                   6408: 
                   6409: sub digits_to_letters {
                   6410:     my ($input) = @_;
                   6411: 
                   6412:     my @alphabet = ('J', 'A'..'I');
                   6413: 
                   6414:     my @input    = split(//, $input);
                   6415:     my $output ='';
                   6416:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6417: 	if ($input[$i] =~ /\d/) {
                   6418: 	    $output .= $alphabet[$input[$i]];
                   6419: 	} else {
                   6420: 	    $output .= $input[$i];
                   6421: 	}
                   6422:     }
                   6423:     return $output;
                   6424: }
                   6425: 
1.423     albertel 6426: =pod 
                   6427: 
                   6428: =item scantron_parse_scanline
                   6429: 
1.711     bisitz   6430:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6431: 
                   6432:  Arguments:
1.711     bisitz   6433:     line             - The text of the bubblesheet file line to process
1.423     albertel 6434:     whichline        - Line number
1.711     bisitz   6435:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6436:     scan_data        - Hash of extra information about the scanline
                   6437:                        (see scantron_getfile for more information)
                   6438:     just_header      - True if should not process question answers but only
                   6439:                        the stuff to the left of the answers.
1.691     raeburn  6440:     randomorder      - True if randomorder in use
                   6441:     randompick       - True if randompick in use
                   6442:     sequence         - Exam folder URL
                   6443:     master_seq       - Ref to array containing symbs in exam folder
                   6444:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6445:                        (corresponding values are resource objects)
                   6446:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6447:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6448:                        are refs to an array of resource objects, ordered
                   6449:                        according to order used for CODE, when randomorder
                   6450:                        and or randompick are in use.
                   6451:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6452:                        for current line to question number used for same question
                   6453:                         in "Master Sequence" (as seen by Course Coordinator).
                   6454:     startline        - Ref to hash where key is question number (0 is first)
                   6455:                        and value is number of first bubble line for current 
                   6456:                        student or code-based randompick and/or randomorder.
                   6457:     totalref         - Ref of scalar used to score total number of bubble
                   6458:                        lines needed for responses in a scan line (used when
                   6459:                        randompick in use. 
                   6460:     
1.423     albertel 6461:  Returns:
                   6462:    Hash containing the result of parsing the scanline
                   6463: 
                   6464:    Keys are all proceeded by the string 'scantron.'
                   6465: 
                   6466:        CODE    - the CODE in use for this scanline
                   6467:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6468:                  by the operator
                   6469:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6470:                             CODEs were selected, but the usage has been
                   6471:                             forced by the operator
1.556     weissno  6472:        ID  - student/employee ID
1.423     albertel 6473:        PaperID - if used, the ID number printed on the sheet when the 
                   6474:                  paper was scanned
                   6475:        FirstName - first name from the sheet
                   6476:        LastName  - last name from the sheet
                   6477: 
                   6478:      if just_header was not true these key may also exist
                   6479: 
1.447     foxr     6480:        missingerror - a list of bubble ranges that are considered to be answers
                   6481:                       to a single question that don't have any bubbles filled in.
                   6482:                       Of the form questionnumber:firstbubblenumber:count.
                   6483:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6484:                       to a single question that have more than one bubble filled in.
                   6485:                       Of the form questionnumber::firstbubblenumber:count
                   6486:    
                   6487:                 In the above, count is the number of bubble responses in the
                   6488:                 input line needed to represent the possible answers to the question.
                   6489:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6490:                 per line would have count = 2.
                   6491: 
1.423     albertel 6492:        maxquest     - the number of the last bubble line that was parsed
                   6493: 
                   6494:        (<number> starts at 1)
                   6495:        <number>.answer - zero or more letters representing the selected
                   6496:                          letters from the scanline for the bubble line 
                   6497:                          <number>.
                   6498:                          if blank there was either no bubble or there where
                   6499:                          multiple bubbles, (consult the keys missingerror and
                   6500:                          doubleerror if this is an error condition)
                   6501: 
                   6502: =cut
                   6503: 
1.82      albertel 6504: sub scantron_parse_scanline {
1.691     raeburn  6505:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6506:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6507:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6508: 
1.82      albertel 6509:     my %record;
1.691     raeburn  6510:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6511:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6512: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6513: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6514: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6515: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6516: 	    $record{'scantron.CODE'}=substr($data,
                   6517: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6518: 					    $$scantron_config{'CODElength'});
1.191     albertel 6519: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6520: 		$record{'scantron.useCODE'}=1;
                   6521: 	    }
1.192     albertel 6522: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6523: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6524: 	    }
1.82      albertel 6525: 	} else {
                   6526: 	    #FIXME interpret first N questions
                   6527: 	}
                   6528:     }
1.83      albertel 6529:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6530: 				  $$scantron_config{'IDlength'});
1.157     albertel 6531:     $record{'scantron.PaperID'}=
                   6532: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6533: 	       $$scantron_config{'PaperIDlength'});
                   6534:     $record{'scantron.FirstName'}=
                   6535: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6536: 	       $$scantron_config{'FirstNamelength'});
                   6537:     $record{'scantron.LastName'}=
                   6538: 	substr($data,$$scantron_config{'LastName'}-1,
                   6539: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6540:     if ($just_header) { return \%record; }
1.194     albertel 6541: 
1.82      albertel 6542:     my @alphabet=('A'..'Z');
                   6543:     my $questnum=0;
1.447     foxr     6544:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6545: 
1.691     raeburn  6546:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6547:     if ($randompick || $randomorder) {
                   6548:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6549:                                          $master_seq,$symb_to_resource,
                   6550:                                          $partids_by_symb,$orderedforcode,
                   6551:                                          $respnumlookup,$startline);
                   6552:         if ($total) {
                   6553:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6554:         }
                   6555:         if (ref($totalref)) {
                   6556:             $$totalref = $total;
                   6557:         }
                   6558:     }
                   6559:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6560:     chomp($questions);		# Get rid of any trailing \n.
                   6561:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6562:     while (length($questions)) {
1.691     raeburn  6563:         my $answers_needed;
                   6564:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6565:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6566:         } else {
                   6567: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6568:         }
1.503     raeburn  6569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6570:                              || 1;
                   6571:         $questnum++;
                   6572:         my $quest_id = $questnum;
                   6573:         my $currentquest = substr($questions,0,$answer_length);
                   6574:         $questions       = substr($questions,$answer_length);
                   6575:         if (length($currentquest) < $answer_length) { next; }
                   6576: 
1.691     raeburn  6577:         my $subdivided;
                   6578:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6579:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6580:         } else {
                   6581:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6582:         }
                   6583:         if ($subdivided =~ /,/) {
1.503     raeburn  6584:             my $subquestnum = 1;
                   6585:             my $subquestions = $currentquest;
1.691     raeburn  6586:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6587:             foreach my $subans (@subanswers_needed) {
                   6588:                 my $subans_length =
                   6589:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6590:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6591:                 $subquestions   = substr($subquestions,$subans_length);
                   6592:                 $quest_id = "$questnum.$subquestnum";
                   6593:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6594:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6595:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6596:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6597:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6598:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6599:                 } else {
                   6600:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6601:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6602:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6603:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6604:                 }
                   6605:                 $subquestnum ++;
                   6606:             }
                   6607:         } else {
                   6608:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6609:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6610:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6611:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6612:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6613:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6614:             } else {
                   6615:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6616:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6617:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6618:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6619:             }
                   6620:         }
                   6621:     }
                   6622:     $record{'scantron.maxquest'}=$questnum;
                   6623:     return \%record;
                   6624: }
1.447     foxr     6625: 
1.691     raeburn  6626: sub get_master_seq {
                   6627:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6628:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6629:                    (ref($symb_to_resource) eq 'HASH'));
                   6630:     my $resource_error;
                   6631:     foreach my $resource (@{$resources}) {
                   6632:         my $ressymb;
                   6633:         if (ref($resource)) {
                   6634:             $ressymb = $resource->symb();
                   6635:             push(@{$master_seq},$ressymb);
                   6636:             $symb_to_resource->{$ressymb} = $resource;
                   6637:         } else {
                   6638:             $resource_error = 1;
                   6639:             last;
                   6640:         }
                   6641:     }
                   6642:     return $resource_error;
                   6643: }
                   6644: 
                   6645: sub get_respnum_lookups {
                   6646:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6647:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6648:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6649:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6650:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6651:                    (ref($startline) eq 'HASH'));
                   6652:     my ($user,$scancode);
                   6653:     if ((exists($record->{'scantron.CODE'})) &&
                   6654:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6655:         $scancode = $record->{'scantron.CODE'};
                   6656:     } else {
                   6657:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6658:     }
                   6659:     my @mapresources =
                   6660:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6661:                      $orderedforcode);
                   6662:     my $total = 0;
                   6663:     my $count = 0;
                   6664:     foreach my $resource (@mapresources) {
                   6665:         my $id = $resource->id();
                   6666:         my $symb = $resource->symb();
                   6667:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6668:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6669:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6670:                 if ($respnum ne '') {
                   6671:                     $respnumlookup->{$count} = $respnum;
                   6672:                     $startline->{$count} = $total;
                   6673:                     $total += $bubble_lines_per_response{$respnum};
                   6674:                     $count ++;
                   6675:                 }
                   6676:             }
                   6677:         }
                   6678:     }
                   6679:     return $total;
                   6680: }
                   6681: 
1.503     raeburn  6682: sub scantron_validator_lettnum {
                   6683:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6684:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6685:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6686: 
                   6687:     # Qon 'letter' implies for each slot in currquest we have:
                   6688:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6689:     #    about anything else (esp. a value of Qoff) for missing
                   6690:     #    bubbles.
                   6691:     #
                   6692:     # Qon 'number' implies each slot gives a digit that indexes the
                   6693:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6694:     #    and * or ? for double bubbles on a single line.
                   6695:     #
1.447     foxr     6696: 
1.503     raeburn  6697:     my $matchon;
                   6698:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6699:         $matchon = '[A-Z]';
                   6700:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6701:         $matchon = '\d';
                   6702:     }
                   6703:     my $occurrences = 0;
1.691     raeburn  6704:     my $responsenum = $questnum-1;
                   6705:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6706:        $responsenum = $respnumlookup->{$questnum-1} 
                   6707:     }
                   6708:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6709:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6710:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6711:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6712:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6713:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6714:         my @singlelines = split('',$currquest);
                   6715:         foreach my $entry (@singlelines) {
                   6716:             $occurrences = &occurence_count($entry,$matchon);
                   6717:             if ($occurrences > 1) {
                   6718:                 last;
                   6719:             }
1.691     raeburn  6720:         }
1.503     raeburn  6721:     } else {
                   6722:         $occurrences = &occurence_count($currquest,$matchon); 
                   6723:     }
                   6724:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6725:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6726:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6727:             my $bubble = substr($currquest,$ans,1);
                   6728:             if ($bubble =~ /$matchon/ ) {
                   6729:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6730:                     if ($bubble == 0) {
                   6731:                         $bubble = 10; 
                   6732:                     }
                   6733:                     $record->{"scantron.$ansnum.answer"} = 
                   6734:                         $alphabet->[$bubble-1];
                   6735:                 } else {
                   6736:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6737:                 }
                   6738:             } else {
                   6739:                 $record->{"scantron.$ansnum.answer"}='';
                   6740:             }
                   6741:             $ansnum++;
                   6742:         }
                   6743:     } elsif (!defined($currquest)
                   6744:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6745:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6746:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6747:             $record->{"scantron.$ansnum.answer"}='';
                   6748:             $ansnum++;
                   6749:         }
                   6750:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6751:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6752:         }
                   6753:     } else {
                   6754:         if ($$scantron_config{'Qon'} eq 'number') {
                   6755:             $currquest = &digits_to_letters($currquest);            
                   6756:         }
                   6757:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6758:             my $bubble = substr($currquest,$ans,1);
                   6759:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6760:             $ansnum++;
                   6761:         }
                   6762:     }
                   6763:     return $ansnum;
                   6764: }
1.447     foxr     6765: 
1.503     raeburn  6766: sub scantron_validator_positional {
                   6767:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6768:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6769:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6770: 
1.503     raeburn  6771:     # Otherwise there's a positional notation;
                   6772:     # each bubble line requires Qlength items, and there are filled in
                   6773:     # bubbles for each case where there 'Qon' characters.
                   6774:     #
1.447     foxr     6775: 
1.503     raeburn  6776:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6777: 
1.503     raeburn  6778:     # If the split only gives us one element.. the full length of the
                   6779:     # answer string, no bubbles are filled in:
1.447     foxr     6780: 
1.507     raeburn  6781:     if ($answers_needed eq '') {
                   6782:         return;
                   6783:     }
                   6784: 
1.503     raeburn  6785:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6786:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6787:             $record->{"scantron.$ansnum.answer"}='';
                   6788:             $ansnum++;
                   6789:         }
                   6790:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6791:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6792:         }
                   6793:     } elsif (scalar(@array) == 2) {
                   6794:         my $location = length($array[0]);
                   6795:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6796:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6797:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6798:             if ($ans eq $line_num) {
                   6799:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6800:             } else {
                   6801:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6802:             }
                   6803:             $ansnum++;
                   6804:          }
                   6805:     } else {
                   6806:         #  If there's more than one instance of a bubble character
                   6807:         #  That's a double bubble; with positional notation we can
                   6808:         #  record all the bubbles filled in as well as the
                   6809:         #  fact this response consists of multiple bubbles.
                   6810:         #
1.691     raeburn  6811:         my $responsenum = $questnum-1;
                   6812:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6813:             $responsenum = $respnumlookup->{$questnum-1}
                   6814:         }
                   6815:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6816:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6817:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6818:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6819:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6820:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6821:             my $doubleerror = 0;
                   6822:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6823:                    (!$doubleerror)) {
                   6824:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6825:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6826:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6827:                if (length(@currarray) > 2) {
                   6828:                    $doubleerror = 1;
                   6829:                } 
                   6830:             }
                   6831:             if ($doubleerror) {
                   6832:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6833:             }
                   6834:         } else {
                   6835:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6836:         }
                   6837:         my $item = $ansnum;
                   6838:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6839:             $record->{"scantron.$item.answer"} = '';
                   6840:             $item ++;
                   6841:         }
1.447     foxr     6842: 
1.503     raeburn  6843:         my @ans=@array;
                   6844:         my $i=0;
                   6845:         my $increment = 0;
                   6846:         while ($#ans) {
                   6847:             $i+=length($ans[0]) + $increment;
                   6848:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6849:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6850:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6851:             shift(@ans);
                   6852:             $increment = 1;
                   6853:         }
                   6854:         $ansnum += $answers_needed;
1.82      albertel 6855:     }
1.503     raeburn  6856:     return $ansnum;
1.82      albertel 6857: }
                   6858: 
1.423     albertel 6859: =pod
                   6860: 
                   6861: =item scantron_add_delay
                   6862: 
                   6863:    Adds an error message that occurred during the grading phase to a
                   6864:    queue of messages to be shown after grading pass is complete
                   6865: 
                   6866:  Arguments:
1.424     albertel 6867:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6868:    $scanline    - the scanline that caused the error
                   6869:    $errormesage - the error message
                   6870:    $errorcode   - a numeric code for the error
                   6871: 
                   6872:  Side Effects:
1.424     albertel 6873:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6874: 
                   6875: =cut
                   6876: 
1.82      albertel 6877: sub scantron_add_delay {
1.140     albertel 6878:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6879:     push(@$delayqueue,
                   6880: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6881: 	  'ecode' => $errorcode }
                   6882: 	 );
1.82      albertel 6883: }
                   6884: 
1.423     albertel 6885: =pod
                   6886: 
                   6887: =item scantron_find_student
                   6888: 
1.424     albertel 6889:    Finds the username for the current scanline
                   6890: 
                   6891:   Arguments:
                   6892:    $scantron_record - hash result from scantron_parse_scanline
                   6893:    $scan_data       - hash of correction information 
                   6894:                       (see &scantron_getfile() form more information)
                   6895:    $idmap           - hash from &username_to_idmap()
                   6896:    $line            - number of current scanline
                   6897:  
                   6898:   Returns:
                   6899:    Either 'username:domain' or undef if unknown
                   6900: 
1.423     albertel 6901: =cut
                   6902: 
1.82      albertel 6903: sub scantron_find_student {
1.157     albertel 6904:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6905:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6906:     if ($scanID =~ /^\s*$/) {
                   6907:  	return &scan_data($scan_data,"$line.user");
                   6908:     }
1.83      albertel 6909:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6910:  	if (lc($id) eq lc($scanID)) {
                   6911:  	    return $$idmap{$id};
                   6912:  	}
1.83      albertel 6913:     }
                   6914:     return undef;
                   6915: }
                   6916: 
1.423     albertel 6917: =pod
                   6918: 
                   6919: =item scantron_filter
                   6920: 
1.424     albertel 6921:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6922:    hidden resources was selected
                   6923: 
1.423     albertel 6924: =cut
                   6925: 
1.83      albertel 6926: sub scantron_filter {
                   6927:     my ($curres)=@_;
1.331     albertel 6928: 
                   6929:     if (ref($curres) && $curres->is_problem()) {
                   6930: 	# if the user has asked to not have either hidden
                   6931: 	# or 'randomout' controlled resources to be graded
                   6932: 	# don't include them
                   6933: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6934: 	    && $curres->randomout) {
                   6935: 	    return 0;
                   6936: 	}
1.83      albertel 6937: 	return 1;
                   6938:     }
                   6939:     return 0;
1.82      albertel 6940: }
                   6941: 
1.423     albertel 6942: =pod
                   6943: 
                   6944: =item scantron_process_corrections
                   6945: 
1.424     albertel 6946:    Gets correction information out of submitted form data and corrects
                   6947:    the scanline
                   6948: 
1.423     albertel 6949: =cut
                   6950: 
1.157     albertel 6951: sub scantron_process_corrections {
                   6952:     my ($r) = @_;
1.754     raeburn  6953:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6954:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6955:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6956:     my $which=$env{'form.scantron_line'};
1.200     albertel 6957:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6958:     my ($skip,$err,$errmsg);
1.257     albertel 6959:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6960: 	$skip=1;
1.257     albertel 6961:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6962: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6963: 	    $env{'form.scantron_domain'};
1.157     albertel 6964: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6965: 	($line,$err,$errmsg)=
                   6966: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6967: 				     'ID',{'newid'=>$newid,
1.257     albertel 6968: 				    'username'=>$env{'form.scantron_username'},
                   6969: 				    'domain'=>$env{'form.scantron_domain'}});
                   6970:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6971: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6972: 	my $newCODE;
1.192     albertel 6973: 	my %args;
1.190     albertel 6974: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6975: 	    $newCODE='use_unfound';
1.190     albertel 6976: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6977: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6978: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6979: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6980: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6981: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6982: 	}
1.257     albertel 6983: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6984: 	    $args{'CODE_ignore_dup'}=1;
                   6985: 	}
                   6986: 	$args{'CODE'}=$newCODE;
1.186     albertel 6987: 	($line,$err,$errmsg)=
                   6988: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6989: 				     'CODE',\%args);
1.257     albertel 6990:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6991: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6992: 	    ($line,$err,$errmsg)=
                   6993: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6994: 					 $which,'answer',
                   6995: 					 { 'question'=>$question,
1.503     raeburn  6996: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6997:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6998: 	    if ($err) { last; }
                   6999: 	}
                   7000:     }
                   7001:     if ($err) {
1.703     bisitz   7002:         $r->print(
                   7003:             '<p class="LC_error">'
                   7004:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7005:                 $errmsg)
1.704     raeburn  7006:            .'</p>');
1.157     albertel 7007:     } else {
1.200     albertel 7008: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7009: 	&scantron_putfile($scanlines,$scan_data);
                   7010:     }
                   7011: }
                   7012: 
1.423     albertel 7013: =pod
                   7014: 
                   7015: =item reset_skipping_status
                   7016: 
1.424     albertel 7017:    Forgets the current set of remember skipped scanlines (and thus
                   7018:    reverts back to considering all lines in the
                   7019:    scantron_skipped_<filename> file)
                   7020: 
1.423     albertel 7021: =cut
                   7022: 
1.200     albertel 7023: sub reset_skipping_status {
                   7024:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7025:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7026:     &scantron_putfile(undef,$scan_data);
                   7027: }
                   7028: 
1.423     albertel 7029: =pod
                   7030: 
                   7031: =item start_skipping
                   7032: 
1.424     albertel 7033:    Marks a scanline to be skipped. 
                   7034: 
1.423     albertel 7035: =cut
                   7036: 
1.376     albertel 7037: sub start_skipping {
1.200     albertel 7038:     my ($scan_data,$i)=@_;
                   7039:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7040:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7041: 	$remembered{$i}=2;
                   7042:     } else {
                   7043: 	$remembered{$i}=1;
                   7044:     }
1.200     albertel 7045:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7046: }
                   7047: 
1.423     albertel 7048: =pod
                   7049: 
                   7050: =item should_be_skipped
                   7051: 
1.424     albertel 7052:    Checks whether a scanline should be skipped.
                   7053: 
1.423     albertel 7054: =cut
                   7055: 
1.200     albertel 7056: sub should_be_skipped {
1.376     albertel 7057:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7058:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7059: 	# not redoing old skips
1.376     albertel 7060: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7061: 	return 0;
                   7062:     }
                   7063:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7064: 
                   7065:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7066: 	return 0;
                   7067:     }
1.200     albertel 7068:     return 1;
                   7069: }
                   7070: 
1.423     albertel 7071: =pod
                   7072: 
                   7073: =item remember_current_skipped
                   7074: 
1.424     albertel 7075:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7076:    file and remembers them into scan_data for later use.
                   7077: 
1.423     albertel 7078: =cut
                   7079: 
1.200     albertel 7080: sub remember_current_skipped {
                   7081:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7082:     my %to_remember;
                   7083:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7084: 	if ($scanlines->{'skipped'}[$i]) {
                   7085: 	    $to_remember{$i}=1;
                   7086: 	}
                   7087:     }
1.376     albertel 7088: 
1.200     albertel 7089:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7090:     &scantron_putfile(undef,$scan_data);
                   7091: }
                   7092: 
1.423     albertel 7093: =pod
                   7094: 
                   7095: =item check_for_error
                   7096: 
1.424     albertel 7097:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7098:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7099:     something went wrong.
                   7100: 
1.423     albertel 7101: =cut
                   7102: 
1.200     albertel 7103: sub check_for_error {
                   7104:     my ($r,$result)=@_;
                   7105:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7106: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7107:     }
                   7108: }
1.157     albertel 7109: 
1.423     albertel 7110: =pod
                   7111: 
                   7112: =item scantron_warning_screen
                   7113: 
1.424     albertel 7114:    Interstitial screen to make sure the operator has selected the
                   7115:    correct options before we start the validation phase.
                   7116: 
1.423     albertel 7117: =cut
                   7118: 
1.203     albertel 7119: sub scantron_warning_screen {
1.650     raeburn  7120:     my ($button_text,$symb)=@_;
1.257     albertel 7121:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7122:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7123:     my $CODElist;
1.284     albertel 7124:     if ($scantron_config{'CODElocation'} &&
                   7125: 	$scantron_config{'CODEstart'} &&
                   7126: 	$scantron_config{'CODElength'}) {
                   7127: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7128: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7129: 	$CODElist=
1.492     albertel 7130: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7131: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7132:     }
1.663     raeburn  7133:     my $lastbubblepoints;
                   7134:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7135:         $lastbubblepoints =
                   7136:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7137:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7138:     }
1.770     raeburn  7139:     return '
1.203     albertel 7140: <p>
1.492     albertel 7141: <span class="LC_warning">
1.705     raeburn  7142: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7143: </p>
                   7144: <table>
1.492     albertel 7145: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7146: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7147: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7148: </table>
1.680     raeburn  7149: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7150: '.&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  7151: ';
1.203     albertel 7152: }
                   7153: 
1.423     albertel 7154: =pod
                   7155: 
                   7156: =item scantron_do_warning
                   7157: 
1.424     albertel 7158:    Check if the operator has picked something for all required
                   7159:    fields. Error out if something is missing.
                   7160: 
1.423     albertel 7161: =cut
                   7162: 
1.203     albertel 7163: sub scantron_do_warning {
1.608     www      7164:     my ($r,$symb)=@_;
1.203     albertel 7165:     if (!$symb) {return '';}
1.324     albertel 7166:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7167:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7168:     if ( $env{'form.selectpage'} eq '' ||
                   7169: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7170: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7171: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7172: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7173: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7174: 	} 
1.257     albertel 7175: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7176: 	    $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  7177: 	}
1.257     albertel 7178: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7179: 	    $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  7180: 	}
1.237     albertel 7181:     } else {
1.650     raeburn  7182: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7183:         my ($checksec,@possibles) = &gradable_sections();
                   7184:         my $gradesections;
                   7185:         if ($checksec) {
                   7186:             my $file=$env{'form.scantron_selectfile'};
                   7187:             if (&valid_file($file)) {
                   7188:                 my %bysec = &scantron_get_sections();
                   7189:                 my $table;
                   7190:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7191:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7192:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7193:                              &Apache::loncommon::start_data_table_header_row().
                   7194:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7195:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7196:                     if ($bysec{'none'}) {
                   7197:                         $table .= &Apache::loncommon::start_data_table_row().
                   7198:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7199:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7200:                     }
                   7201:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7202:                         next if ($sec eq 'none');
                   7203:                         $table .= &Apache::loncommon::start_data_table_row().
                   7204:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7205:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7206:                     }
                   7207:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7208:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7209:                                       '<p>'.$table.'</p>';
                   7210:                     if (@possibles) {
                   7211:                         $gradesections .= '<p>'.
                   7212:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7213:                                               scalar(@possibles)).'<br />'.
                   7214:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7215:                                               '<i>'.$checksec.'</i>').' ';
                   7216:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7217:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7218:                         }
                   7219:                         $gradesections .= '</p>';
                   7220:                     }
                   7221:                 }
                   7222:             } else {
                   7223:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7224:             }
                   7225:         }
1.663     raeburn  7226:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7227: 	$r->print('
1.770     raeburn  7228: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7229: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7230: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7231: ');
1.237     albertel 7232:     }
1.614     www      7233:     $r->print("</form><br />");
1.203     albertel 7234:     return '';
                   7235: }
                   7236: 
1.423     albertel 7237: =pod
                   7238: 
                   7239: =item scantron_form_start
                   7240: 
1.424     albertel 7241:     html hidden input for remembering all selected grading options
                   7242: 
1.423     albertel 7243: =cut
                   7244: 
1.203     albertel 7245: sub scantron_form_start {
                   7246:     my ($max_bubble)=@_;
                   7247:     my $result= <<SCANTRONFORM;
                   7248: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7249:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7250:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7251:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7252:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7253:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7254:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7255:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7256:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7257:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7258: SCANTRONFORM
1.447     foxr     7259: 
                   7260:   my $line = 0;
                   7261:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7262:        my $chunk =
                   7263: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7264:        $chunk .=
                   7265: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7266:        $chunk .= 
                   7267:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7268:        $chunk .=
                   7269:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7270:        $chunk .=
                   7271:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7272:        $result .= $chunk;
                   7273:        $line++;
1.691     raeburn  7274:     }
1.203     albertel 7275:     return $result;
                   7276: }
                   7277: 
1.423     albertel 7278: =pod
                   7279: 
                   7280: =item scantron_validate_file
                   7281: 
1.659     raeburn  7282:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7283: 
                   7284:     Also processes any necessary information resets that need to
                   7285:     occur before validation begins (ignore previous corrections,
                   7286:     restarting the skipped records processing)
                   7287: 
1.423     albertel 7288: =cut
                   7289: 
1.157     albertel 7290: sub scantron_validate_file {
1.608     www      7291:     my ($r,$symb) = @_;
1.157     albertel 7292:     if (!$symb) {return '';}
1.324     albertel 7293:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7294:     
1.703     bisitz   7295:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7296:     # them when doing the corrections reset
1.257     albertel 7297:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7298: 	&reset_skipping_status();
                   7299:     }
1.257     albertel 7300:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7301: 	&remember_current_skipped();
1.257     albertel 7302: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7303:     }
                   7304: 
1.257     albertel 7305:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7306: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7307: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7308: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7309: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7310:     }
1.200     albertel 7311: 
1.257     albertel 7312:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7313: 	&scantron_process_corrections($r);
                   7314:     }
1.770     raeburn  7315: 
                   7316:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7317:     my ($checksec,@gradable);
                   7318:     if ($env{'request.course.sec'}) {
                   7319:         ($checksec,my @possibles) = &gradable_sections();
                   7320:         if ($checksec) {
                   7321:             if (@possibles) {
                   7322:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7323:                 if (@chosensecs) {
                   7324:                     foreach my $sec (@chosensecs) {
                   7325:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7326:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7327:                                 push(@gradable,$sec);
                   7328:                             }
                   7329:                         }
                   7330:                     }
                   7331:                 }
                   7332:             }
                   7333:             $r->print('<p><table>');
                   7334:             if (@gradable) {
                   7335:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7336:                 $r->print(
                   7337:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7338:             } else {
                   7339:                 $r->print(
                   7340:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7341:             }
                   7342:             $r->print('</table></p>');
                   7343:         }
                   7344:     }
                   7345:     $r->rflush();
                   7346: 
1.157     albertel 7347:     #get the student pick code ready
                   7348:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7349:     my $nav_error;
1.754     raeburn  7350:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7351:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7352:     if ($nav_error) {
                   7353:         $r->print(&navmap_errormsg());
                   7354:         return '';
                   7355:     }
1.203     albertel 7356:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7357:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7358:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7359:     }
1.157     albertel 7360:     $r->print($result);
                   7361:     
1.334     albertel 7362:     my @validate_phases=( 'sequence',
                   7363: 			  'ID',
1.157     albertel 7364: 			  'CODE',
                   7365: 			  'doublebubble',
                   7366: 			  'missingbubbles');
1.257     albertel 7367:     if (!$env{'form.validatepass'}) {
                   7368: 	$env{'form.validatepass'} = 0;
1.157     albertel 7369:     }
1.257     albertel 7370:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7371:     my %skipbysec=();
1.448     foxr     7372: 
1.157     albertel 7373:     my $stop=0;
                   7374:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7375: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7376: 	$r->rflush();
1.691     raeburn  7377:      
1.157     albertel 7378: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7379: 	{
                   7380: 	    no strict 'refs';
1.770     raeburn  7381:             my @extras=();
                   7382:             if ($validate_phases[$currentphase] eq 'ID') {
                   7383:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7384:             }
                   7385: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7386: 	}
                   7387:     }
                   7388:     if (!$stop) {
1.650     raeburn  7389: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7390:         my $secinfo;
                   7391:         if (keys(%skipbysec) > 0) {
                   7392:             my $seclist = '<ul>';
                   7393:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7394:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7395:             }
                   7396:             $seclist .= '</ul>';
                   7397:             $secinfo = '<p class="LC_info">'.
                   7398:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7399:                            $seclist).
                   7400:                        '</p>';
                   7401:         }
1.542     raeburn  7402: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7403:                   $secinfo.$warning.
1.542     raeburn  7404:                   &mt('Perform verification for each student after storage of submissions?').
                   7405:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7406:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7407:                   ('&nbsp;'x3).'<label>'.
                   7408:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7409:                   '</label></span><br />'.
                   7410:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7411:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7412:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7413:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7414:     } else {
                   7415: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7416: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7417:     }
                   7418:     if ($stop) {
1.334     albertel 7419: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7420: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7421: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7422: 
1.650     raeburn  7423: 	    $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 7424: 	} else {
1.503     raeburn  7425:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7426: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7427:             } else {
1.539     riegler  7428:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7429:             }
1.492     albertel 7430: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7431: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7432: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7433: 	}
1.157     albertel 7434:     }
1.614     www      7435:     $r->print(" </form><br />");
1.157     albertel 7436:     return '';
                   7437: }
                   7438: 
1.423     albertel 7439: 
                   7440: =pod
                   7441: 
                   7442: =item scantron_remove_file
                   7443: 
1.659     raeburn  7444:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7445:    scantron_original_<filename> is never removed
                   7446: 
                   7447: 
1.423     albertel 7448: =cut
                   7449: 
1.200     albertel 7450: sub scantron_remove_file {
1.192     albertel 7451:     my ($which)=@_;
1.257     albertel 7452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7454:     my $file='scantron_';
1.200     albertel 7455:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7456: 	$file.=$which.'_';
1.192     albertel 7457:     } else {
                   7458: 	return 'refused';
                   7459:     }
1.257     albertel 7460:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7461:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7462: }
                   7463: 
1.423     albertel 7464: 
                   7465: =pod
                   7466: 
                   7467: =item scantron_remove_scan_data
                   7468: 
1.659     raeburn  7469:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7470:    data file.  (In the case that both the are doing skipped records we need
                   7471:    to remember the old skipped lines for the time being so that element
                   7472:    persists for a while.)
                   7473: 
1.423     albertel 7474: =cut
                   7475: 
1.200     albertel 7476: sub scantron_remove_scan_data {
1.257     albertel 7477:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7478:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7479:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7480:     my @todelete;
1.257     albertel 7481:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7482:     foreach my $key (@keys) {
                   7483: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7484: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7485: 		$key=~/remember_skipping/) {
                   7486: 		next;
                   7487: 	    }
1.192     albertel 7488: 	    push(@todelete,$key);
                   7489: 	}
                   7490:     }
1.200     albertel 7491:     my $result;
1.192     albertel 7492:     if (@todelete) {
1.491     albertel 7493: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7494: 				       \@todelete,$cdom,$cname);
                   7495:     } else {
                   7496: 	$result = 'ok';
1.192     albertel 7497:     }
                   7498:     return $result;
                   7499: }
                   7500: 
1.423     albertel 7501: 
                   7502: =pod
                   7503: 
                   7504: =item scantron_getfile
                   7505: 
1.659     raeburn  7506:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7507:     the scan_data hash
                   7508:   
                   7509:   Arguments:
                   7510:     None
                   7511: 
                   7512:   Returns:
                   7513:     2 hash references
                   7514: 
                   7515:      - first one has 
                   7516:          orig      -
                   7517:          corrected -
                   7518:          skipped   -  each of which points to an array ref of the specified
                   7519:                       file broken up into individual lines
                   7520:          count     - number of scanlines
                   7521:  
                   7522:      - second is the scan_data hash possible keys are
1.425     albertel 7523:        ($number refers to scanline numbered $number and thus the key affects
                   7524:         only that scanline
                   7525:         $bubline refers to the specific bubble line element and the aspects
                   7526:         refers to that specific bubble line element)
                   7527: 
                   7528:        $number.user - username:domain to use
                   7529:        $number.CODE_ignore_dup 
                   7530:                     - ignore the duplicate CODE error 
                   7531:        $number.useCODE
                   7532:                     - use the CODE in the scanline as is
                   7533:        $number.no_bubble.$bubline
                   7534:                     - it is valid that there is no bubbled in bubble
                   7535:                       at $number $bubline
                   7536:        remember_skipping
                   7537:                     - a frozen hash containing keys of $number and values
                   7538:                       of either 
                   7539:                         1 - we are on a 'do skipped records pass' and plan
                   7540:                             on processing this line
                   7541:                         2 - we are on a 'do skipped records pass' and this
                   7542:                             scanline has been marked to skip yet again
1.424     albertel 7543: 
1.423     albertel 7544: =cut
                   7545: 
1.157     albertel 7546: sub scantron_getfile {
1.200     albertel 7547:     #FIXME really would prefer a scantron directory
1.257     albertel 7548:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7550:     my $lines;
                   7551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7552: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7553:     my %scanlines;
                   7554:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7555:     my $temp=$scanlines{'orig'};
                   7556:     $scanlines{'count'}=$#$temp;
                   7557: 
                   7558:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7559: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7560:     if ($lines eq '-1') {
                   7561: 	$scanlines{'corrected'}=[];
                   7562:     } else {
                   7563: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7564:     }
                   7565:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7566: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7567:     if ($lines eq '-1') {
                   7568: 	$scanlines{'skipped'}=[];
                   7569:     } else {
                   7570: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7571:     }
1.175     albertel 7572:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7573:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7574:     my %scan_data = @tmp;
                   7575:     return (\%scanlines,\%scan_data);
                   7576: }
                   7577: 
1.423     albertel 7578: =pod
                   7579: 
                   7580: =item lonnet_putfile
                   7581: 
1.424     albertel 7582:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7583: 
                   7584:  Arguments:
                   7585:    $contents - data to store
                   7586:    $filename - filename to store $contents into
                   7587: 
                   7588:  Returns:
                   7589:    result value from &Apache::lonnet::finishuserfileupload
                   7590: 
1.423     albertel 7591: =cut
                   7592: 
1.157     albertel 7593: sub lonnet_putfile {
                   7594:     my ($contents,$filename)=@_;
1.257     albertel 7595:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7596:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7597:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7598:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7599: 
                   7600: }
                   7601: 
1.423     albertel 7602: =pod
                   7603: 
                   7604: =item scantron_putfile
                   7605: 
1.659     raeburn  7606:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7607:     scan_data hash. (Does not modify the original version only the
                   7608:     corrected and skipped versions.
                   7609: 
                   7610:  Arguments:
                   7611:     $scanlines - hash ref that looks like the first return value from
                   7612:                  &scantron_getfile()
                   7613:     $scan_data - hash ref that looks like the second return value from
                   7614:                  &scantron_getfile()
                   7615: 
1.423     albertel 7616: =cut
                   7617: 
1.157     albertel 7618: sub scantron_putfile {
                   7619:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7620:     #FIXME really would prefer a scantron directory
1.257     albertel 7621:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7622:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7623:     if ($scanlines) {
                   7624: 	my $prefix='scantron_';
1.157     albertel 7625: # no need to update orig, shouldn't change
                   7626: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7627: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7628: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7629: 			$prefix.'corrected_'.
1.257     albertel 7630: 			$env{'form.scantron_selectfile'});
1.200     albertel 7631: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7632: 			$prefix.'skipped_'.
1.257     albertel 7633: 			$env{'form.scantron_selectfile'});
1.200     albertel 7634:     }
1.175     albertel 7635:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7636: }
                   7637: 
1.423     albertel 7638: =pod
                   7639: 
                   7640: =item scantron_get_line
                   7641: 
1.424     albertel 7642:    Returns the correct version of the scanline
                   7643: 
                   7644:  Arguments:
                   7645:     $scanlines - hash ref that looks like the first return value from
                   7646:                  &scantron_getfile()
                   7647:     $scan_data - hash ref that looks like the second return value from
                   7648:                  &scantron_getfile()
                   7649:     $i         - number of the requested line (starts at 0)
                   7650: 
                   7651:  Returns:
                   7652:    A scanline, (either the original or the corrected one if it
                   7653:    exists), or undef if the requested scanline should be
                   7654:    skipped. (Either because it's an skipped scanline, or it's an
                   7655:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7656:    pass.
                   7657: 
1.423     albertel 7658: =cut
                   7659: 
1.157     albertel 7660: sub scantron_get_line {
1.200     albertel 7661:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7662:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7663:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7664:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7665:     return $scanlines->{'orig'}[$i]; 
                   7666: }
                   7667: 
1.423     albertel 7668: =pod
                   7669: 
                   7670: =item scantron_todo_count
                   7671: 
1.424     albertel 7672:     Counts the number of scanlines that need processing.
                   7673: 
                   7674:  Arguments:
                   7675:     $scanlines - hash ref that looks like the first return value from
                   7676:                  &scantron_getfile()
                   7677:     $scan_data - hash ref that looks like the second return value from
                   7678:                  &scantron_getfile()
                   7679: 
                   7680:  Returns:
                   7681:     $count - number of scanlines to process
                   7682: 
1.423     albertel 7683: =cut
                   7684: 
1.200     albertel 7685: sub get_todo_count {
                   7686:     my ($scanlines,$scan_data)=@_;
                   7687:     my $count=0;
                   7688:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7689: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7690: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7691: 	$count++;
                   7692:     }
                   7693:     return $count;
                   7694: }
                   7695: 
1.423     albertel 7696: =pod
                   7697: 
                   7698: =item scantron_put_line
                   7699: 
1.659     raeburn  7700:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7701:     data file.
                   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         - line number to update
                   7709:     $newline   - contents of the updated scanline
                   7710:     $skip      - if true make the line for skipping and update the
                   7711:                  'skipped' file
                   7712: 
1.423     albertel 7713: =cut
                   7714: 
1.157     albertel 7715: sub scantron_put_line {
1.200     albertel 7716:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7717:     if ($skip) {
                   7718: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7719: 	&start_skipping($scan_data,$i);
1.157     albertel 7720: 	return;
                   7721:     }
                   7722:     $scanlines->{'corrected'}[$i]=$newline;
                   7723: }
                   7724: 
1.423     albertel 7725: =pod
                   7726: 
                   7727: =item scantron_clear_skip
                   7728: 
1.424     albertel 7729:    Remove a line from the 'skipped' file
                   7730: 
                   7731:  Arguments:
                   7732:     $scanlines - hash ref that looks like the first return value from
                   7733:                  &scantron_getfile()
                   7734:     $scan_data - hash ref that looks like the second return value from
                   7735:                  &scantron_getfile()
                   7736:     $i         - line number to update
                   7737: 
1.423     albertel 7738: =cut
                   7739: 
1.376     albertel 7740: sub scantron_clear_skip {
                   7741:     my ($scanlines,$scan_data,$i)=@_;
                   7742:     if (exists($scanlines->{'skipped'}[$i])) {
                   7743: 	undef($scanlines->{'skipped'}[$i]);
                   7744: 	return 1;
                   7745:     }
                   7746:     return 0;
                   7747: }
                   7748: 
1.423     albertel 7749: =pod
                   7750: 
                   7751: =item scantron_filter_not_exam
                   7752: 
1.424     albertel 7753:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7754:    filter out resources that are not marked as 'exam' mode
                   7755: 
1.423     albertel 7756: =cut
                   7757: 
1.334     albertel 7758: sub scantron_filter_not_exam {
                   7759:     my ($curres)=@_;
                   7760:     
                   7761:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7762: 	# if the user has asked to not have either hidden
                   7763: 	# or 'randomout' controlled resources to be graded
                   7764: 	# don't include them
                   7765: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7766: 	    && $curres->randomout) {
                   7767: 	    return 0;
                   7768: 	}
                   7769: 	return 1;
                   7770:     }
                   7771:     return 0;
                   7772: }
                   7773: 
1.423     albertel 7774: =pod
                   7775: 
                   7776: =item scantron_validate_sequence
                   7777: 
1.424     albertel 7778:     Validates the selected sequence, checking for resource that are
                   7779:     not set to exam mode.
                   7780: 
1.423     albertel 7781: =cut
                   7782: 
1.334     albertel 7783: sub scantron_validate_sequence {
                   7784:     my ($r,$currentphase) = @_;
                   7785: 
                   7786:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7787:     unless (ref($navmap)) {
                   7788:         $r->print(&navmap_errormsg());
                   7789:         return (1,$currentphase);
                   7790:     }
1.334     albertel 7791:     my (undef,undef,$sequence)=
                   7792: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7793: 
                   7794:     my $map=$navmap->getResourceByUrl($sequence);
                   7795: 
                   7796:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7797:                                     value="ignore" />');
                   7798:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7799: 	my @resources=
                   7800: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7801: 	if (@resources) {
1.675     bisitz   7802: 	    $r->print(
                   7803:                 '<p class="LC_warning">'
                   7804:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7805:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7806:                    .' work correctly.')
                   7807:                .'</p>'
                   7808:             );
1.334     albertel 7809: 	    return (1,$currentphase);
                   7810: 	}
                   7811:     }
                   7812: 
                   7813:     return (0,$currentphase+1);
                   7814: }
                   7815: 
1.423     albertel 7816: 
                   7817: 
1.157     albertel 7818: sub scantron_validate_ID {
1.770     raeburn  7819:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7820:     
                   7821:     #get student info
                   7822:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7823:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7824:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7825: 
                   7826:     #get scantron line setup
1.754     raeburn  7827:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7828:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7829: 
                   7830:     my $nav_error;
1.649     raeburn  7831:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7832:     if ($nav_error) {
                   7833:         $r->print(&navmap_errormsg());
                   7834:         return(1,$currentphase);
                   7835:     }
1.157     albertel 7836: 
                   7837:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7838:     my $unsavedskips = 0;
1.157     albertel 7839:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7840: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7841: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7842: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7843: 						 $scan_data);
                   7844: 	my $id=$$scan_record{'scantron.ID'};
                   7845: 	my $found;
                   7846: 	foreach my $checkid (keys(%idmap)) {
                   7847: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7848: 	}
                   7849: 	if ($found) {
                   7850: 	    my $username=$idmap{$found};
1.770     raeburn  7851:             if ($checksec) {
                   7852:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7853:                     my $stusec = $classlist->{$username}->[$secidx];
                   7854:                     if ($stusec ne $checksec) {
                   7855:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7856:                             my $skip=1;
                   7857:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7858:                             if (ref($skipbysec) eq 'HASH') {
                   7859:                                 if ($stusec eq '') {
                   7860:                                     $skipbysec->{'none'} ++;
                   7861:                                 } else {
                   7862:                                     $skipbysec->{$stusec} ++;
                   7863:                                 }
                   7864:                             }
                   7865:                             $unsavedskips ++;
                   7866:                             next;
                   7867:                         }
                   7868:                     }
                   7869:                 }
                   7870:             }
1.157     albertel 7871: 	    if ($found{'ids'}{$found}) {
                   7872: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7873: 					 $line,'duplicateID',$found);
1.770     raeburn  7874:                 if ($unsavedskips) {
                   7875:                     &scantron_putfile($scanlines,$scan_data);
                   7876:                     $unsavedskips = 0;
                   7877:                 }
1.194     albertel 7878: 		return(1,$currentphase);
1.157     albertel 7879: 	    } elsif ($found{'usernames'}{$username}) {
                   7880: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7881: 					 $line,'duplicateID',$username);
1.770     raeburn  7882:                 if ($unsavedskips) {
                   7883:                     &scantron_putfile($scanlines,$scan_data);
                   7884:                     $unsavedskips = 0;
                   7885:                 }
1.194     albertel 7886: 		return(1,$currentphase);
1.157     albertel 7887: 	    }
1.186     albertel 7888: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7889: 	    $found{'ids'}{$found}++;
                   7890: 	    $found{'usernames'}{$username}++;
                   7891: 	} else {
                   7892: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7893: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7894:                 if (($checksec && $username ne '')) {
                   7895:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7896:                         my $stusec = $classlist->{$username}->[$secidx];
                   7897:                         if ($stusec ne $checksec) {
                   7898:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7899:                                 my $skip=1;
                   7900:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7901:                                 if (ref($skipbysec) eq 'HASH') {
                   7902:                                     if ($stusec eq '') {
                   7903:                                         $skipbysec->{'none'} ++;
                   7904:                                     } else {
                   7905:                                         $skipbysec->{$stusec} ++;
                   7906:                                     }
                   7907:                                 }
                   7908:                                 $unsavedskips ++;
                   7909:                                 next;
                   7910:                             }
                   7911:                         }
                   7912:                     }
                   7913: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7914: 		    &scantron_get_correction($r,$i,$scan_record,
                   7915: 					     \%scantron_config,
                   7916: 					     $line,'duplicateID',$username);
1.770     raeburn  7917:                     if ($unsavedskips) {
                   7918:                         &scantron_putfile($scanlines,$scan_data);
                   7919:                         $unsavedskips = 0;
                   7920:                     }
1.194     albertel 7921: 		    return(1,$currentphase);
1.157     albertel 7922: 		} elsif (!defined($username)) {
                   7923: 		    &scantron_get_correction($r,$i,$scan_record,
                   7924: 					     \%scantron_config,
                   7925: 					     $line,'incorrectID');
1.770     raeburn  7926:                     if ($unsavedskips) {
                   7927:                         &scantron_putfile($scanlines,$scan_data);
                   7928:                         $unsavedskips = 0;
                   7929:                     }
1.194     albertel 7930: 		    return(1,$currentphase);
1.157     albertel 7931: 		}
                   7932: 		$found{'usernames'}{$username}++;
                   7933: 	    } else {
                   7934: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7935: 					 $line,'incorrectID');
1.770     raeburn  7936:                 if ($unsavedskips) {
                   7937:                     &scantron_putfile($scanlines,$scan_data);
                   7938:                     $unsavedskips = 0;
                   7939:                 }
1.194     albertel 7940: 		return(1,$currentphase);
1.157     albertel 7941: 	    }
                   7942: 	}
                   7943:     }
1.770     raeburn  7944:     if ($unsavedskips) {
                   7945:         &scantron_putfile($scanlines,$scan_data);
                   7946:         $unsavedskips = 0;
                   7947:     }
1.157     albertel 7948:     return (0,$currentphase+1);
                   7949: }
                   7950: 
1.770     raeburn  7951: sub scantron_get_sections {
                   7952:     my %bysec;
                   7953:     if ($env{'form.scantron_format'} ne '') {
                   7954:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   7955:         my ($scanlines,$scan_data)=&scantron_getfile();
                   7956:         my $classlist=&Apache::loncoursedata::get_classlist();
                   7957:         my %idmap=&username_to_idmap($classlist);
                   7958:         foreach my $key (keys(%idmap)) {
                   7959:             my $lckey = lc($key);
                   7960:             $idmap{$lckey} = $idmap{$key};
                   7961:         }
                   7962:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   7963:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7964:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7965:             if ($line=~/^[\s\cz]*$/) { next; }
                   7966:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7967:                                                      $scan_data);
                   7968:             my $id=lc($$scan_record{'scantron.ID'});
                   7969:             if (exists($idmap{$id})) {
                   7970:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   7971:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   7972:                     if ($stusec eq '') {
                   7973:                         $bysec{'none'} ++;
                   7974:                     } else {
                   7975:                         $bysec{$stusec} ++;
                   7976:                     }
                   7977:                 }
                   7978:             }
                   7979:         }
                   7980:     }
                   7981:     return %bysec;
                   7982: }
1.423     albertel 7983: 
1.157     albertel 7984: sub scantron_get_correction {
1.691     raeburn  7985:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7986:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7987: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7988: #to show both the current line and the previous one and allow skipping
                   7989: #the previous one or the current one
                   7990: 
1.333     albertel 7991:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7992:         $r->print(
                   7993:             '<p class="LC_warning">'
                   7994:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7995:                 "<b>$error</b>",
                   7996:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7997:            ."</p> \n");
1.157     albertel 7998:     } else {
1.658     bisitz   7999:         $r->print(
                   8000:             '<p class="LC_warning">'
                   8001:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8002:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8003:            ."</p> \n");
                   8004:     }
                   8005:     my $message =
                   8006:         '<p>'
                   8007:        .&mt('The ID on the form is [_1]',
                   8008:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8009:        .'<br />'
1.665     raeburn  8010:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8011:             $$scan_record{'scantron.LastName'},
                   8012:             $$scan_record{'scantron.FirstName'})
                   8013:        .'</p>';
1.242     albertel 8014: 
1.157     albertel 8015:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8016:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8017:                            # Array populated for doublebubble or
                   8018:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8019:                            # to validate radio button checking   
                   8020: 
1.157     albertel 8021:     if ($error =~ /ID$/) {
1.186     albertel 8022: 	if ($error eq 'incorrectID') {
1.658     bisitz   8023:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8024: 		      "</p>\n");
1.157     albertel 8025: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8026:             $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 8027: 	}
1.242     albertel 8028: 	$r->print($message);
1.492     albertel 8029: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8030: 	$r->print("\n<ul><li> ");
                   8031: 	#FIXME it would be nice if this sent back the user ID and
                   8032: 	#could do partial userID matches
                   8033: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8034: 				       'scantron_username','scantron_domain'));
                   8035: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8036: 	$r->print("\n:\n".
1.257     albertel 8037: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8038: 
                   8039: 	$r->print('</li>');
1.186     albertel 8040:     } elsif ($error =~ /CODE$/) {
                   8041: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8042: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8043: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8044: 	    $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 8045: 	}
1.658     bisitz   8046: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8047: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8048:                  ."</p>\n");
1.242     albertel 8049: 	$r->print($message);
1.658     bisitz   8050: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8051: 	$r->print("\n<br /> ");
1.194     albertel 8052: 	my $i=0;
1.273     albertel 8053: 	if ($error eq 'incorrectCODE' 
                   8054: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8055: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8056: 	    if ($closest > 0) {
                   8057: 		foreach my $testcode (@{$closest}) {
                   8058: 		    my $checked='';
1.569     bisitz   8059: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8060: 		    $r->print("
                   8061:    <label>
1.569     bisitz   8062:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8063:        ".&mt("Use the similar CODE [_1] instead.",
                   8064: 	    "<b><tt>".$testcode."</tt></b>")."
                   8065:     </label>
                   8066:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8067: 		    $r->print("\n<br />");
                   8068: 		    $i++;
                   8069: 		}
1.194     albertel 8070: 	    }
                   8071: 	}
1.273     albertel 8072: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8073: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8074: 	    $r->print("
                   8075:     <label>
1.569     bisitz   8076:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8077:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8078: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8079:     </label>");
1.273     albertel 8080: 	    $r->print("\n<br />");
                   8081: 	}
1.194     albertel 8082: 
1.597     wenzelju 8083: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8084: function change_radio(field) {
1.190     albertel 8085:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8086:     var i;
                   8087:     for (i=0;i<slct.length;i++) {
                   8088:         if (slct[i].value==field) { slct[i].checked=true; }
                   8089:     }
                   8090: }
                   8091: ENDSCRIPT
1.187     albertel 8092: 	my $href="/adm/pickcode?".
1.359     www      8093: 	   "form=".&escape("scantronupload").
                   8094: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8095: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8096: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8097: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8098: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8099: 	    $r->print("
                   8100:     <label>
                   8101:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8102:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8103: 	     "<a target='_blank' href='$href'>","</a>")."
                   8104:     </label> 
1.558     bisitz   8105:     ".&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 8106: 	    $r->print("\n<br />");
                   8107: 	}
1.492     albertel 8108: 	$r->print("
                   8109:     <label>
                   8110:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8111:        ".&mt("Use [_1] as the CODE.",
                   8112: 	     "</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 8113: 	$r->print("\n<br /><br />");
1.157     albertel 8114:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8115: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8116: 
                   8117: 	# The form field scantron_questions is acutally a list of line numbers.
                   8118: 	# represented by this form so:
                   8119: 
1.691     raeburn  8120: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8121:                                                 $respnumlookup,$startline);
1.497     foxr     8122: 
1.157     albertel 8123: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8124: 		  $line_list.'" />');
1.242     albertel 8125: 	$r->print($message);
1.492     albertel 8126: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8127: 	foreach my $question (@{$arg}) {
1.503     raeburn  8128: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8129:                                                    $scan_record, $error,
                   8130:                                                    $randomorder,$randompick,
                   8131:                                                    $respnumlookup,$startline);
1.524     raeburn  8132:             push(@lines_to_correct,@linenums);
1.157     albertel 8133: 	}
1.503     raeburn  8134:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8135:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8136: 	$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 8137: 	$r->print($message);
1.492     albertel 8138: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8139: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8140: 
1.503     raeburn  8141: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8142: 	# a list of question numbers. Therefore:
                   8143: 	#
1.691     raeburn  8144: 
                   8145: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8146:                                                 $respnumlookup,$startline);
1.497     foxr     8147: 
1.157     albertel 8148: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8149: 		  $line_list.'" />');
1.157     albertel 8150: 	foreach my $question (@{$arg}) {
1.503     raeburn  8151: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8152:                                                    $scan_record, $error,
                   8153:                                                    $randomorder,$randompick,
                   8154:                                                    $respnumlookup,$startline);
1.524     raeburn  8155:             push(@lines_to_correct,@linenums);
1.157     albertel 8156: 	}
1.503     raeburn  8157:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8158:     } else {
                   8159: 	$r->print("\n<ul>");
                   8160:     }
                   8161:     $r->print("\n</li></ul>");
1.497     foxr     8162: }
                   8163: 
1.503     raeburn  8164: sub verify_bubbles_checked {
                   8165:     my (@ansnums) = @_;
                   8166:     my $ansnumstr = join('","',@ansnums);
                   8167:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8168:     &js_escape(\$warning);
1.767     raeburn  8169:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8170: function verify_bubble_radio(form) {
                   8171:     var ansnumArray = new Array ("$ansnumstr");
                   8172:     var need_bubble_count = 0;
                   8173:     for (var i=0; i<ansnumArray.length; i++) {
                   8174:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8175:             var bubble_picked = 0; 
                   8176:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8177:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8178:                     bubble_picked = 1;
                   8179:                 }
                   8180:             }
                   8181:             if (bubble_picked == 0) {
                   8182:                 need_bubble_count ++;
                   8183:             }
                   8184:         }
                   8185:     }
                   8186:     if (need_bubble_count) {
                   8187:         alert("$warning");
                   8188:         return;
                   8189:     }
                   8190:     form.submit(); 
                   8191: }
                   8192: ENDSCRIPT
                   8193:     return $output;
                   8194: }
                   8195: 
1.497     foxr     8196: =pod
                   8197: 
                   8198: =item  questions_to_line_list
1.157     albertel 8199: 
1.497     foxr     8200: Converts a list of questions into a string of comma separated
                   8201: line numbers in the answer sheet used by the questions.  This is
                   8202: used to fill in the scantron_questions form field.
                   8203: 
                   8204:   Arguments:
                   8205:      questions    - Reference to an array of questions.
1.691     raeburn  8206:      randomorder  - True if randomorder in use.
                   8207:      randompick   - True if randompick in use.
                   8208:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8209:                      for current line to question number used for same question
                   8210:                      in "Master Seqence" (as seen by Course Coordinator).
                   8211:      startline    - Reference to hash where key is question number (0 is first)
                   8212:                     and key is number of first bubble line for current student
                   8213:                     or code-based randompick and/or randomorder.
1.693     raeburn  8214: 
1.497     foxr     8215: =cut
                   8216: 
                   8217: 
                   8218: sub questions_to_line_list {
1.691     raeburn  8219:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8220:     my @lines;
                   8221: 
1.503     raeburn  8222:     foreach my $item (@{$questions}) {
                   8223:         my $question = $item;
                   8224:         my ($first,$count,$last);
                   8225:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8226:             $question = $1;
                   8227:             my $subquestion = $2;
1.691     raeburn  8228:             my $responsenum = $question-1;
                   8229:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8230:                 $responsenum = $respnumlookup->{$question-1};
                   8231:                 if (ref($startline) eq 'HASH') {
                   8232:                     $first = $startline->{$question-1} + 1;
                   8233:                 }
                   8234:             } else {
                   8235:                 $first = $first_bubble_line{$responsenum} + 1;
                   8236:             }
                   8237:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8238:             my $subcount = 1;
                   8239:             while ($subcount<$subquestion) {
                   8240:                 $first += $subans[$subcount-1];
                   8241:                 $subcount ++;
                   8242:             }
                   8243:             $count = $subans[$subquestion-1];
                   8244:         } else {
1.691     raeburn  8245:             my $responsenum = $question-1;
                   8246:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8247:                 $responsenum = $respnumlookup->{$question-1};
                   8248:                 if (ref($startline) eq 'HASH') {
                   8249:                     $first = $startline->{$question-1} + 1;
                   8250:                 }
                   8251:             } else {
                   8252:                 $first = $first_bubble_line{$responsenum} + 1;
                   8253:             }
                   8254: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8255:         }
1.506     raeburn  8256:         $last = $first+$count-1;
1.503     raeburn  8257:         push(@lines, ($first..$last));
1.497     foxr     8258:     }
                   8259:     return join(',', @lines);
                   8260: }
                   8261: 
                   8262: =pod 
                   8263: 
                   8264: =item prompt_for_corrections
                   8265: 
                   8266: Prompts for a potentially multiline correction to the
                   8267: user's bubbling (factors out common code from scantron_get_correction
                   8268: for multi and missing bubble cases).
                   8269: 
                   8270:  Arguments:
                   8271:    $r           - Apache request object.
                   8272:    $question    - The question number to prompt for.
                   8273:    $scan_config - The scantron file configuration hash.
                   8274:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8275:    $error       - Type of error
1.691     raeburn  8276:    $randomorder - True if randomorder in use.
                   8277:    $randompick  - True if randompick in use.
                   8278:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8279:                     for current line to question number used for same question
                   8280:                     in "Master Seqence" (as seen by Course Coordinator).
                   8281:    $startline   - Reference to hash where key is question number (0 is first)
                   8282:                   and value is number of first bubble line for current student
                   8283:                   or code-based randompick and/or randomorder.
                   8284: 
1.497     foxr     8285: 
                   8286:  Implicit inputs:
                   8287:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8288:                                   Numbered from 0 (but question numbers are from
                   8289:                                   1.
                   8290:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8291:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8292:                                   type problems render as separate sub-questions, 
1.503     raeburn  8293:                                   in exam mode. This hash contains a 
                   8294:                                   comma-separated list of the lines per 
                   8295:                                   sub-question.
1.510     raeburn  8296:    %responsetype_per_response   - essayresponse, formularesponse,
                   8297:                                   stringresponse, imageresponse, reactionresponse,
                   8298:                                   and organicresponse type problem parts can have
1.503     raeburn  8299:                                   multiple lines per response if the weight
                   8300:                                   assigned exceeds 10.  In this case, only
                   8301:                                   one bubble per line is permitted, but more 
                   8302:                                   than one line might contain bubbles, e.g.
                   8303:                                   bubbling of: line 1 - J, line 2 - J, 
                   8304:                                   line 3 - B would assign 22 points.  
1.497     foxr     8305: 
                   8306: =cut
                   8307: 
                   8308: sub prompt_for_corrections {
1.691     raeburn  8309:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8310:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8311:     my ($current_line,$lines);
                   8312:     my @linenums;
                   8313:     my $questionnum = $question;
1.691     raeburn  8314:     my ($first,$responsenum);
1.503     raeburn  8315:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8316:         $question = $1;
                   8317:         my $subquestion = $2;
1.691     raeburn  8318:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8319:             $responsenum = $respnumlookup->{$question-1};
                   8320:             if (ref($startline) eq 'HASH') {
                   8321:                 $first = $startline->{$question-1};
                   8322:             }
                   8323:         } else {
                   8324:             $responsenum = $question-1;
1.714     raeburn  8325:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8326:         }
                   8327:         $current_line = $first + 1 ;
                   8328:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8329:         my $subcount = 1;
                   8330:         while ($subcount<$subquestion) {
                   8331:             $current_line += $subans[$subcount-1];
                   8332:             $subcount ++;
                   8333:         }
                   8334:         $lines = $subans[$subquestion-1];
                   8335:     } else {
1.691     raeburn  8336:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8337:             $responsenum = $respnumlookup->{$question-1};
                   8338:             if (ref($startline) eq 'HASH') { 
                   8339:                 $first = $startline->{$question-1};
                   8340:             }
                   8341:         } else {
                   8342:             $responsenum = $question-1;
                   8343:             $first = $first_bubble_line{$responsenum};
                   8344:         }
                   8345:         $current_line = $first + 1;
                   8346:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8347:     }
1.497     foxr     8348:     if ($lines > 1) {
1.503     raeburn  8349:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8350:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8351:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8352:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8353:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8354:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8355:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8356:             $r->print(
                   8357:                 &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)
                   8358:                .'<br /><br />'
                   8359:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8360:                .'<br />'
                   8361:                .&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.')
                   8362:                .'<br />'
                   8363:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8364:                .'<br /><br />'
                   8365:             );
1.503     raeburn  8366:         } else {
                   8367:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8368:         }
1.497     foxr     8369:     }
                   8370:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8371:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8372: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8373: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8374:         push(@linenums,$current_line);
1.497     foxr     8375: 	$current_line++;
                   8376:     }
                   8377:     if ($lines > 1) {
                   8378: 	$r->print("<hr /><br />");
                   8379:     }
1.503     raeburn  8380:     return @linenums;
1.157     albertel 8381: }
1.423     albertel 8382: 
                   8383: =pod
                   8384: 
                   8385: =item scantron_bubble_selector
                   8386:   
                   8387:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8388:    possibly showing the existing the selected bubbles if known
1.423     albertel 8389: 
                   8390:  Arguments:
                   8391:     $r           - Apache request object
1.754     raeburn  8392:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8393:     $line        - Number of the line being displayed.
1.503     raeburn  8394:     $questionnum - Question number (may include subquestion)
                   8395:     $error       - Type of error.
1.497     foxr     8396:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8397: 
                   8398: =cut
                   8399: 
1.157     albertel 8400: sub scantron_bubble_selector {
1.503     raeburn  8401:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8402:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8403: 
                   8404:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8405:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8406:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8407:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8408:             $max=$$scan_config{'BubblesPerRow'};
                   8409:             if (($scmode eq 'number') && ($max > 10)) {
                   8410:                 $max = 10;
                   8411:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8412:                 $max = 26;
                   8413:             }
                   8414:         } else {
                   8415:             $max = 10;
                   8416:         }
                   8417:     }
1.274     albertel 8418: 
1.157     albertel 8419:     my @alphabet=('A'..'Z');
1.503     raeburn  8420:     $r->print(&Apache::loncommon::start_data_table().
                   8421:               &Apache::loncommon::start_data_table_row());
                   8422:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8423:     for (my $i=0;$i<$max+1;$i++) {
                   8424: 	$r->print("\n".'<td align="center">');
                   8425: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8426: 	else { $r->print('&nbsp;'); }
                   8427: 	$r->print('</td>');
                   8428:     }
1.503     raeburn  8429:     $r->print(&Apache::loncommon::end_data_table_row().
                   8430:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8431:     for (my $i=0;$i<$max;$i++) {
                   8432: 	$r->print("\n".
                   8433: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8434: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8435:     }
1.503     raeburn  8436:     my $nobub_checked = ' ';
                   8437:     if ($error eq 'missingbubble') {
                   8438:         $nobub_checked = ' checked = "checked" ';
                   8439:     }
                   8440:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8441: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8442:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8443:               $line.'" value="'.$questionnum.'" /></td>');
                   8444:     $r->print(&Apache::loncommon::end_data_table_row().
                   8445:               &Apache::loncommon::end_data_table());
1.157     albertel 8446: }
                   8447: 
1.423     albertel 8448: =pod
                   8449: 
                   8450: =item num_matches
                   8451: 
1.424     albertel 8452:    Counts the number of characters that are the same between the two arguments.
                   8453: 
                   8454:  Arguments:
                   8455:    $orig - CODE from the scanline
                   8456:    $code - CODE to match against
                   8457: 
                   8458:  Returns:
                   8459:    $count - integer count of the number of same characters between the
                   8460:             two arguments
                   8461: 
1.423     albertel 8462: =cut
                   8463: 
1.194     albertel 8464: sub num_matches {
                   8465:     my ($orig,$code) = @_;
                   8466:     my @code=split(//,$code);
                   8467:     my @orig=split(//,$orig);
                   8468:     my $same=0;
                   8469:     for (my $i=0;$i<scalar(@code);$i++) {
                   8470: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8471:     }
                   8472:     return $same;
                   8473: }
                   8474: 
1.423     albertel 8475: =pod
                   8476: 
                   8477: =item scantron_get_closely_matching_CODEs
                   8478: 
1.424     albertel 8479:    Cycles through all CODEs and finds the set that has the greatest
                   8480:    number of same characters as the provided CODE
                   8481: 
                   8482:  Arguments:
                   8483:    $allcodes - hash ref returned by &get_codes()
                   8484:    $CODE     - CODE from the current scanline
                   8485: 
                   8486:  Returns:
                   8487:    2 element list
                   8488:     - first elements is number of how closely matching the best fit is 
                   8489:       (5 means best set has 5 matching characters)
                   8490:     - second element is an arrary ref containing the set of valid CODEs
                   8491:       that best fit the passed in CODE
                   8492: 
1.423     albertel 8493: =cut
                   8494: 
1.194     albertel 8495: sub scantron_get_closely_matching_CODEs {
                   8496:     my ($allcodes,$CODE)=@_;
                   8497:     my @CODEs;
                   8498:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8499: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8500:     }
                   8501: 
                   8502:     return ($#CODEs,$CODEs[-1]);
                   8503: }
                   8504: 
1.423     albertel 8505: =pod
                   8506: 
                   8507: =item get_codes
                   8508: 
1.424     albertel 8509:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8510:    set of remembered CODEs.
                   8511: 
                   8512:  Arguments:
                   8513:   $old_name - name of the set of remembered CODEs
                   8514:   $cdom     - domain of the course
                   8515:   $cnum     - internal course name
                   8516: 
                   8517:  Returns:
                   8518:   %allcodes - keys are the valid CODEs, values are all 1
                   8519: 
1.423     albertel 8520: =cut
                   8521: 
1.194     albertel 8522: sub get_codes {
1.280     foxr     8523:     my ($old_name, $cdom, $cnum) = @_;
                   8524:     if (!$old_name) {
                   8525: 	$old_name=$env{'form.scantron_CODElist'};
                   8526:     }
                   8527:     if (!$cdom) {
                   8528: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8529:     }
                   8530:     if (!$cnum) {
                   8531: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8532:     }
1.278     albertel 8533:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8534: 				    $cdom,$cnum);
                   8535:     my %allcodes;
                   8536:     if ($result{"type\0$old_name"} eq 'number') {
                   8537: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8538:     } else {
                   8539: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8540:     }
1.194     albertel 8541:     return %allcodes;
                   8542: }
                   8543: 
1.423     albertel 8544: =pod
                   8545: 
                   8546: =item scantron_validate_CODE
                   8547: 
1.424     albertel 8548:    Validates all scanlines in the selected file to not have any
                   8549:    invalid or underspecified CODEs and that none of the codes are
                   8550:    duplicated if this was requested.
                   8551: 
1.423     albertel 8552: =cut
                   8553: 
1.157     albertel 8554: sub scantron_validate_CODE {
                   8555:     my ($r,$currentphase) = @_;
1.754     raeburn  8556:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8557:     if ($scantron_config{'CODElocation'} &&
                   8558: 	$scantron_config{'CODEstart'} &&
                   8559: 	$scantron_config{'CODElength'}) {
1.257     albertel 8560: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8561: 	    &FIXME_blow_up()
                   8562: 	}
                   8563:     } else {
                   8564: 	return (0,$currentphase+1);
                   8565:     }
                   8566:     
                   8567:     my %usedCODEs;
                   8568: 
1.194     albertel 8569:     my %allcodes=&get_codes();
1.186     albertel 8570: 
1.582     raeburn  8571:     my $nav_error;
1.649     raeburn  8572:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8573:     if ($nav_error) {
                   8574:         $r->print(&navmap_errormsg());
                   8575:         return(1,$currentphase);
                   8576:     }
1.447     foxr     8577: 
1.186     albertel 8578:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8579:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8580: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8581: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8582: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8583: 						 $scan_data);
                   8584: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8585: 	my $error=0;
1.224     albertel 8586: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8587: 	    &scantron_get_correction($r,$i,$scan_record,
                   8588: 				     \%scantron_config,
                   8589: 				     $line,'incorrectCODE',\%allcodes);
                   8590: 	    return(1,$currentphase);
                   8591: 	}
1.221     albertel 8592: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8593: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8594: 	    &scantron_get_correction($r,$i,$scan_record,
                   8595: 				     \%scantron_config,
1.194     albertel 8596: 				     $line,'incorrectCODE',\%allcodes);
                   8597: 	    return(1,$currentphase);
1.186     albertel 8598: 	}
1.214     albertel 8599: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8600: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8601: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8602: 	    &scantron_get_correction($r,$i,$scan_record,
                   8603: 				     \%scantron_config,
1.194     albertel 8604: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8605: 	    return(1,$currentphase);
1.186     albertel 8606: 	}
1.524     raeburn  8607: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8608:     }
1.157     albertel 8609:     return (0,$currentphase+1);
                   8610: }
                   8611: 
1.423     albertel 8612: =pod
                   8613: 
                   8614: =item scantron_validate_doublebubble
                   8615: 
1.424     albertel 8616:    Validates all scanlines in the selected file to not have any
                   8617:    bubble lines with multiple bubbles marked.
                   8618: 
1.423     albertel 8619: =cut
                   8620: 
1.157     albertel 8621: sub scantron_validate_doublebubble {
                   8622:     my ($r,$currentphase) = @_;
                   8623:     #get student info
                   8624:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8625:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8626:     my (undef,undef,$sequence)=
                   8627:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8628: 
                   8629:     #get scantron line setup
1.754     raeburn  8630:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8631:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8632: 
                   8633:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8634:     unless (ref($navmap)) {
                   8635:         $r->print(&navmap_errormsg());
                   8636:         return(1,$currentphase);
                   8637:     }
                   8638:     my $map=$navmap->getResourceByUrl($sequence);
                   8639:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8640:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8641:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8642:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8643: 
1.583     raeburn  8644:     my $nav_error;
1.691     raeburn  8645:     if (ref($map)) {
                   8646:         $randomorder = $map->randomorder();
                   8647:         $randompick = $map->randompick();
                   8648:         if ($randomorder || $randompick) {
                   8649:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8650:             if ($nav_error) {
                   8651:                 $r->print(&navmap_errormsg());
                   8652:                 return(1,$currentphase);
                   8653:             }
                   8654:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8655:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8656:         }
                   8657:     } else {
                   8658:         $r->print(&navmap_errormsg());
                   8659:         return(1,$currentphase);
                   8660:     }
                   8661: 
1.649     raeburn  8662:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8663:     if ($nav_error) {
                   8664:         $r->print(&navmap_errormsg());
                   8665:         return(1,$currentphase);
                   8666:     }
1.447     foxr     8667: 
1.157     albertel 8668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8670: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8671: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8672: 						 $scan_data,undef,\%idmap,$randomorder,
                   8673:                                                  $randompick,$sequence,\@master_seq,
                   8674:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8675:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8676: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8677: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8678: 				 'doublebubble',
1.691     raeburn  8679: 				 $$scan_record{'scantron.doubleerror'},
                   8680:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8681:     	return (1,$currentphase);
                   8682:     }
                   8683:     return (0,$currentphase+1);
                   8684: }
                   8685: 
1.423     albertel 8686: 
1.503     raeburn  8687: sub scantron_get_maxbubble {
1.649     raeburn  8688:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8689:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8690: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8691: 	&restore_bubble_lines();
1.257     albertel 8692: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8693:     }
1.330     albertel 8694: 
1.447     foxr     8695:     my (undef, undef, $sequence) =
1.257     albertel 8696: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8697: 
1.447     foxr     8698:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8699:     unless (ref($navmap)) {
                   8700:         if (ref($nav_error)) {
                   8701:             $$nav_error = 1;
                   8702:         }
1.591     raeburn  8703:         return;
1.582     raeburn  8704:     }
1.191     albertel 8705:     my $map=$navmap->getResourceByUrl($sequence);
                   8706:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8707:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8708: 
                   8709:     &Apache::lonxml::clear_problem_counter();
                   8710: 
1.557     raeburn  8711:     my $uname       = $env{'user.name'};
                   8712:     my $udom        = $env{'user.domain'};
1.435     foxr     8713:     my $cid         = $env{'request.course.id'};
                   8714:     my $total_lines = 0;
                   8715:     %bubble_lines_per_response = ();
1.447     foxr     8716:     %first_bubble_line         = ();
1.503     raeburn  8717:     %subdivided_bubble_lines   = ();
                   8718:     %responsetype_per_response = ();
1.691     raeburn  8719:     %masterseq_id_responsenum  = ();
1.554     raeburn  8720: 
1.447     foxr     8721:     my $response_number = 0;
                   8722:     my $bubble_line     = 0;
1.191     albertel 8723:     foreach my $resource (@resources) {
1.691     raeburn  8724:         my $resid = $resource->id(); 
1.672     raeburn  8725:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8726:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8727:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8728: 	    foreach my $part_id (@{$parts}) {
                   8729:                 my $lines;
                   8730: 
                   8731: 	        # TODO - make this a persistent hash not an array.
                   8732: 
                   8733:                 # optionresponse, matchresponse and rankresponse type items 
                   8734:                 # render as separate sub-questions in exam mode.
                   8735:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8736:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8737:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8738:                     my ($numbub,$numshown);
                   8739:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8740:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8741:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8742:                         }
                   8743:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8744:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8745:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8746:                         }
                   8747:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8748:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8749:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8750:                         }
                   8751:                     }
                   8752:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8753:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8754:                     }
1.649     raeburn  8755:                     my $bubbles_per_row =
                   8756:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8757:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8758:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8759:                         $inner_bubble_lines++;
                   8760:                     }
                   8761:                     for (my $i=0; $i<$numshown; $i++) {
                   8762:                         $subdivided_bubble_lines{$response_number} .= 
                   8763:                             $inner_bubble_lines.',';
                   8764:                     }
                   8765:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8766:                     $lines = $numshown * $inner_bubble_lines;
                   8767:                 } else {
                   8768:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8769:                 }
1.542     raeburn  8770: 
                   8771:                 $first_bubble_line{$response_number} = $bubble_line;
                   8772: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8773:                 $responsetype_per_response{$response_number} = 
                   8774:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8775:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8776: 	        $response_number++;
                   8777: 
                   8778: 	        $bubble_line +=  $lines;
                   8779: 	        $total_lines +=  $lines;
                   8780: 	    }
                   8781:         }
                   8782:     }
1.552     raeburn  8783:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8784: 
                   8785:     &save_bubble_lines();
                   8786:     $env{'form.scantron_maxbubble'} =
                   8787: 	$total_lines;
                   8788:     return $env{'form.scantron_maxbubble'};
                   8789: }
1.523     raeburn  8790: 
1.649     raeburn  8791: sub bubblesheet_bubbles_per_row {
                   8792:     my ($scantron_config) = @_;
                   8793:     my $bubbles_per_row;
                   8794:     if (ref($scantron_config) eq 'HASH') {
                   8795:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8796:     }
                   8797:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8798:         $bubbles_per_row = 10;
                   8799:     }
                   8800:     return $bubbles_per_row;
                   8801: }
                   8802: 
1.157     albertel 8803: sub scantron_validate_missingbubbles {
                   8804:     my ($r,$currentphase) = @_;
                   8805:     #get student info
                   8806:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8807:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8808:     my (undef,undef,$sequence)=
                   8809:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8810: 
                   8811:     #get scantron line setup
1.754     raeburn  8812:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8813:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8814: 
                   8815:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8816:     unless (ref($navmap)) {
                   8817:         $r->print(&navmap_errormsg());
                   8818:         return(1,$currentphase);
                   8819:     }
                   8820: 
                   8821:     my $map=$navmap->getResourceByUrl($sequence);
                   8822:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8823:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8824:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8825:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8826: 
1.582     raeburn  8827:     my $nav_error;
1.691     raeburn  8828:     if (ref($map)) {
                   8829:         $randomorder = $map->randomorder();
                   8830:         $randompick = $map->randompick();
                   8831:         if ($randomorder || $randompick) {
                   8832:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8833:             if ($nav_error) {
                   8834:                 $r->print(&navmap_errormsg());
                   8835:                 return(1,$currentphase);
                   8836:             }
                   8837:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8838:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8839:         }
                   8840:     } else {
                   8841:         $r->print(&navmap_errormsg());
                   8842:         return(1,$currentphase);
                   8843:     }
                   8844: 
                   8845: 
1.649     raeburn  8846:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8847:     if ($nav_error) {
1.691     raeburn  8848:         $r->print(&navmap_errormsg());
1.693     raeburn  8849:         return(1,$currentphase);
1.582     raeburn  8850:     }
1.691     raeburn  8851: 
1.157     albertel 8852:     if (!$max_bubble) { $max_bubble=2**31; }
                   8853:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8854: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8855: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8856: 	my $scan_record =
                   8857:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8858: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8859:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8860:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8861: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8862: 	my @to_correct;
1.470     foxr     8863: 	
                   8864: 	# Probably here's where the error is...
                   8865: 
1.157     albertel 8866: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8867:             my $lastbubble;
                   8868:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8869:                my $question = $1;
                   8870:                my $subquestion = $2;
1.691     raeburn  8871:                my ($first,$responsenum);
                   8872:                if ($randomorder || $randompick) {
                   8873:                    $responsenum = $respnumlookup{$question-1};
                   8874:                    $first = $startline{$question-1};
                   8875:                } else {
                   8876:                    $responsenum = $question-1; 
                   8877:                    $first = $first_bubble_line{$responsenum};
                   8878:                }
                   8879:                if (!defined($first)) { next; }
                   8880:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8881:                my $subcount = 1;
                   8882:                while ($subcount<$subquestion) {
                   8883:                    $first += $subans[$subcount-1];
                   8884:                    $subcount ++;
                   8885:                }
                   8886:                my $count = $subans[$subquestion-1];
                   8887:                $lastbubble = $first + $count;
                   8888:             } else {
1.691     raeburn  8889:                my ($first,$responsenum);
                   8890:                if ($randomorder || $randompick) {
                   8891:                    $responsenum = $respnumlookup{$missing-1};
                   8892:                    $first = $startline{$missing-1};
                   8893:                } else {
                   8894:                    $responsenum = $missing-1;
                   8895:                    $first = $first_bubble_line{$responsenum};
                   8896:                }
                   8897:                if (!defined($first)) { next; }
                   8898:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8899:             }
                   8900:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8901: 	    push(@to_correct,$missing);
                   8902: 	}
                   8903: 	if (@to_correct) {
                   8904: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8905: 				     $line,'missingbubble',\@to_correct,
                   8906:                                      $randomorder,$randompick,\%respnumlookup,
                   8907:                                      \%startline);
1.157     albertel 8908: 	    return (1,$currentphase);
                   8909: 	}
                   8910: 
                   8911:     }
                   8912:     return (0,$currentphase+1);
                   8913: }
                   8914: 
1.663     raeburn  8915: sub hand_bubble_option {
                   8916:     my (undef, undef, $sequence) =
                   8917:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8918:     return if ($sequence eq '');
                   8919:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8920:     unless (ref($navmap)) {
                   8921:         return;
                   8922:     }
                   8923:     my $needs_hand_bubbles;
                   8924:     my $map=$navmap->getResourceByUrl($sequence);
                   8925:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8926:     foreach my $res (@resources) {
                   8927:         if (ref($res)) {
                   8928:             if ($res->is_problem()) {
                   8929:                 my $partlist = $res->parts();
                   8930:                 foreach my $part (@{ $partlist }) {
                   8931:                     my @types = $res->responseType($part);
                   8932:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8933:                         $needs_hand_bubbles = 1;
                   8934:                         last;
                   8935:                     }
                   8936:                 }
                   8937:             }
                   8938:         }
                   8939:     }
                   8940:     if ($needs_hand_bubbles) {
1.754     raeburn  8941:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8942:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8943:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8944:                &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 />').
                   8945:                '<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  8946:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8947:     }
                   8948:     return;
                   8949: }
1.423     albertel 8950: 
1.82      albertel 8951: sub scantron_process_students {
1.608     www      8952:     my ($r,$symb) = @_;
1.513     foxr     8953: 
1.257     albertel 8954:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8955:     if (!$symb) {
                   8956: 	return '';
                   8957:     }
1.324     albertel 8958:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8959: 
1.754     raeburn  8960:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8961:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8962:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8963:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8964:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8965:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8966:     unless (ref($navmap)) {
                   8967:         $r->print(&navmap_errormsg());
                   8968:         return '';
1.691     raeburn  8969:     }
1.83      albertel 8970:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8971:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8972:         %grader_randomlists_by_symb);
1.677     raeburn  8973:     if (ref($map)) {
                   8974:         $randomorder = $map->randomorder();
1.689     raeburn  8975:         $randompick = $map->randompick();
1.691     raeburn  8976:     } else {
                   8977:         $r->print(&navmap_errormsg());
                   8978:         return '';
1.677     raeburn  8979:     }
1.691     raeburn  8980:     my $nav_error;
1.83      albertel 8981:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8982:     if ($randomorder || $randompick) {
                   8983:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8984:         if ($nav_error) {
                   8985:             $r->print(&navmap_errormsg());
                   8986:             return '';
                   8987:         }
                   8988:     }
1.557     raeburn  8989:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8990:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8991: 
1.554     raeburn  8992:     my ($uname,$udom);
1.82      albertel 8993:     my $result= <<SCANTRONFORM;
1.81      albertel 8994: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8995:   <input type="hidden" name="command" value="scantron_configphase" />
                   8996:   $default_form_data
                   8997: SCANTRONFORM
1.82      albertel 8998:     $r->print($result);
                   8999: 
1.770     raeburn  9000:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9001:     my @delayqueue;
1.542     raeburn  9002:     my (%completedstudents,%scandata);
1.770     raeburn  9003: 
1.520     www      9004:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9005:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9006:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9007:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9008:     $r->print('<br />');
1.140     albertel 9009:     my $start=&Time::HiRes::time();
1.158     albertel 9010:     my $i=-1;
1.542     raeburn  9011:     my $started;
1.447     foxr     9012: 
1.649     raeburn  9013:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9014:     if ($nav_error) {
                   9015:         $r->print(&navmap_errormsg());
                   9016:         return '';
                   9017:     }
                   9018: 
1.513     foxr     9019:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9020:     # the user and return.
                   9021: 
                   9022:     if ($ssi_error) {
                   9023: 	$r->print("</form>");
                   9024: 	&ssi_print_error($r);
1.520     www      9025:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9026: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9027:     }
1.447     foxr     9028: 
1.755     raeburn  9029:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9030:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9031:     my %orderedforcode;
1.542     raeburn  9032: 
1.157     albertel 9033:     while ($i<$scanlines->{'count'}) {
                   9034:  	($uname,$udom)=('','');
                   9035:  	$i++;
1.200     albertel 9036:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9037:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9038: 	if ($started) {
1.667     www      9039: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9040: 	}
                   9041: 	$started=1;
1.691     raeburn  9042:         my %respnumlookup = ();
                   9043:         my %startline = ();
                   9044:         my $total;
1.157     albertel 9045:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9046:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9047:                                                  $randompick,$sequence,\@master_seq,
                   9048:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9049:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9050:                                                  \$total);
1.157     albertel 9051:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9052:  					      \%idmap,$i)) {
                   9053:   	    &scantron_add_delay(\@delayqueue,$line,
                   9054:  				'Unable to find a student that matches',1);
                   9055:  	    next;
                   9056:   	}
                   9057:  	if (exists $completedstudents{$uname}) {
                   9058:  	    &scantron_add_delay(\@delayqueue,$line,
                   9059:  				'Student '.$uname.' has multiple sheets',2);
                   9060:  	    next;
                   9061:  	}
1.677     raeburn  9062:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9063:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9064:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9065:                 &scantron_add_delay(\@delayqueue,$line,
                   9066:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9067:                 next;
                   9068:             }
                   9069:         }
1.677     raeburn  9070:         my $user = $uname.':'.$usec;
1.157     albertel 9071:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9072: 
1.677     raeburn  9073:         my $scancode;
                   9074:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9075:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9076:             $scancode = $scan_record->{'scantron.CODE'};
                   9077:         } else {
                   9078:             $scancode = '';
                   9079:         }
                   9080: 
                   9081:         my @mapresources = @resources;
1.689     raeburn  9082:         if ($randomorder || $randompick) {
1.678     raeburn  9083:             @mapresources = 
1.691     raeburn  9084:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9085:                              \%orderedforcode);
1.677     raeburn  9086:         }
1.586     raeburn  9087:         my (%partids_by_symb,$res_error);
1.677     raeburn  9088:         foreach my $resource (@mapresources) {
1.586     raeburn  9089:             my $ressymb;
                   9090:             if (ref($resource)) {
                   9091:                 $ressymb = $resource->symb();
                   9092:             } else {
                   9093:                 $res_error = 1;
                   9094:                 last;
                   9095:             }
1.557     raeburn  9096:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9097:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9098:                 my $currcode;
                   9099:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9100:                     $currcode = $scancode;
                   9101:                 }
1.557     raeburn  9102:                 my ($analysis,$parts) =
1.672     raeburn  9103:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9104:                                               $uname,$udom,undef,$bubbles_per_row,
                   9105:                                               $currcode);
1.557     raeburn  9106:                 $partids_by_symb{$ressymb} = $parts;
                   9107:             } else {
                   9108:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9109:             }
1.554     raeburn  9110:         }
                   9111: 
1.586     raeburn  9112:         if ($res_error) {
                   9113:             &scantron_add_delay(\@delayqueue,$line,
                   9114:                                 'An error occurred while grading student '.$uname,2);
                   9115:             next;
                   9116:         }
                   9117: 
1.330     albertel 9118: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9119:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9120: 
                   9121: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9122: 	    &scantron_putfile($scanlines,$scan_data);
                   9123: 	}
1.161     albertel 9124: 	
1.542     raeburn  9125:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9126:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9127:                                    $bubbles_per_row,$randomorder,$randompick,
                   9128:                                    \%respnumlookup,\%startline) 
                   9129:             eq 'ssi_error') {
1.542     raeburn  9130:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9131:             $r->print("</form>");
                   9132:             &ssi_print_error($r);
                   9133:             &Apache::lonnet::remove_lock($lock);
                   9134:             return '';      # Why return ''?  Beats me.
                   9135:         }
1.513     foxr     9136: 
1.692     raeburn  9137:         if (($scancode) && ($randomorder || $randompick)) {
                   9138:             my $parmresult =
                   9139:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9140:                                                        '0_examcode',2,$scancode,
                   9141:                                                        'string_examcode',$uname,
                   9142:                                                        $udom);
                   9143:         }
1.140     albertel 9144: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9145:         if ($env{'form.verifyrecord'}) {
                   9146:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9147:             if ($randompick) {
                   9148:                 if ($total) {
                   9149:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9150:                 }
                   9151:             }
                   9152: 
1.542     raeburn  9153:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9154:             chomp($studentdata);
                   9155:             $studentdata =~ s/\r$//;
                   9156:             my $studentrecord = '';
                   9157:             my $counter = -1;
1.677     raeburn  9158:             foreach my $resource (@mapresources) {
1.554     raeburn  9159:                 my $ressymb = $resource->symb();
1.542     raeburn  9160:                 ($counter,my $recording) =
                   9161:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9162:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9163:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9164:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9165:                 $studentrecord .= $recording;
                   9166:             }
                   9167:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9168:                 &Apache::lonxml::clear_problem_counter();
                   9169:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9170:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9171:                                            $bubbles_per_row,$randomorder,$randompick,
                   9172:                                            \%respnumlookup,\%startline) 
                   9173:                     eq 'ssi_error') {
1.554     raeburn  9174:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9175:                     $r->print("</form>");
                   9176:                     &ssi_print_error($r);
                   9177:                     &Apache::lonnet::remove_lock($lock);
                   9178:                     delete($completedstudents{$uname});
                   9179:                     return '';
                   9180:                 }
1.542     raeburn  9181:                 $counter = -1;
                   9182:                 $studentrecord = '';
1.677     raeburn  9183:                 foreach my $resource (@mapresources) {
1.554     raeburn  9184:                     my $ressymb = $resource->symb();
1.542     raeburn  9185:                     ($counter,my $recording) =
                   9186:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9187:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9188:                                                  \%scantron_config,\%lettdig,$numletts,
                   9189:                                                  $randomorder,$randompick,\%respnumlookup,
                   9190:                                                  \%startline);
1.542     raeburn  9191:                     $studentrecord .= $recording;
                   9192:                 }
                   9193:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9194:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9195:                     if ($scancode eq '') {
1.658     bisitz   9196:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9197:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9198:                     } else {
1.658     bisitz   9199:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9200:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9201:                     }
                   9202:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9203:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9204:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9205:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9206:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9207:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9208:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9209:                               &Apache::loncommon::end_data_table_row().
                   9210:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9211:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9212:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9213:                               &Apache::loncommon::end_data_table_row().
                   9214:                               &Apache::loncommon::end_data_table().'</p>');
                   9215:                 } else {
                   9216:                     $r->print('<br /><span class="LC_warning">'.
                   9217:                              &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 />'.
                   9218:                              &mt("As a consequence, this user's submission history records two tries.").
                   9219:                                  '</span><br />');
                   9220:                 }
                   9221:             }
                   9222:         }
1.543     raeburn  9223:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9224:     } continue {
1.330     albertel 9225: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9226: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9227:     }
1.140     albertel 9228:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9229:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9230: #    my $lasttime = &Time::HiRes::time()-$start;
                   9231: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9232: 
1.200     albertel 9233:     $r->print("</form>");
1.157     albertel 9234:     return '';
1.75      albertel 9235: }
1.157     albertel 9236: 
1.557     raeburn  9237: sub graders_resources_pass {
1.649     raeburn  9238:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9239:         $bubbles_per_row) = @_;
1.557     raeburn  9240:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9241:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9242:         foreach my $resource (@{$resources}) {
                   9243:             my $ressymb = $resource->symb();
                   9244:             my ($analysis,$parts) =
                   9245:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9246:                                           $env{'user.name'},$env{'user.domain'},
                   9247:                                           1,$bubbles_per_row);
1.557     raeburn  9248:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9249:             if (ref($analysis) eq 'HASH') {
                   9250:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9251:                     $grader_randomlists_by_symb->{$ressymb} =
                   9252:                         $analysis->{'parts_withrandomlist'};
                   9253:                 }
                   9254:             }
                   9255:         }
                   9256:     }
                   9257:     return;
                   9258: }
                   9259: 
1.678     raeburn  9260: =pod
                   9261: 
                   9262: =item users_order
                   9263: 
                   9264:   Returns array of resources in current map, ordered based on either CODE,
                   9265:   if this is a CODEd exam, or based on student's identity if this is a 
                   9266:   "NAMEd" exam.
                   9267: 
1.691     raeburn  9268:   Should be used when randomorder and/or randompick applied when the 
                   9269:   corresponding exam was printed, prior to students completing bubblesheets 
                   9270:   for the version of the exam the student received.
1.678     raeburn  9271: 
                   9272: =cut
                   9273: 
                   9274: sub users_order  {
1.691     raeburn  9275:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9276:     my @mapresources;
1.691     raeburn  9277:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9278:         return @mapresources;
1.691     raeburn  9279:     }
                   9280:     if ($scancode) {
                   9281:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9282:             @mapresources = @{$orderedforcode->{$scancode}};
                   9283:         } else {
                   9284:             $env{'form.CODE'} = $scancode;
                   9285:             my $actual_seq =
                   9286:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9287:                                                                $master_seq,
                   9288:                                                                $user,$scancode,1);
                   9289:             if (ref($actual_seq) eq 'ARRAY') {
                   9290:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9291:                 if (ref($orderedforcode) eq 'HASH') {
                   9292:                     if (@mapresources > 0) { 
                   9293:                         $orderedforcode->{$scancode} = \@mapresources;
                   9294:                     }
                   9295:                 }
                   9296:             }
                   9297:             delete($env{'form.CODE'});
1.678     raeburn  9298:         }
                   9299:     } else {
                   9300:         my $actual_seq =
                   9301:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9302:                                                            $master_seq,
1.688     raeburn  9303:                                                            $user,undef,1);
1.678     raeburn  9304:         if (ref($actual_seq) eq 'ARRAY') {
                   9305:             @mapresources = 
                   9306:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9307:         }
1.691     raeburn  9308:     }
                   9309:     return @mapresources;
1.678     raeburn  9310: }
                   9311: 
1.542     raeburn  9312: sub grade_student_bubbles {
1.691     raeburn  9313:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9314:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9315:     my $uselookup = 0;
                   9316:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9317:         (ref($startline) eq 'HASH')) {
                   9318:         $uselookup = 1;
                   9319:     }
                   9320: 
1.554     raeburn  9321:     if (ref($resources) eq 'ARRAY') {
                   9322:         my $count = 0;
                   9323:         foreach my $resource (@{$resources}) {
                   9324:             my $ressymb = $resource->symb();
                   9325:             my %form = ('submitted'      => 'scantron',
                   9326:                         'grade_target'   => 'grade',
                   9327:                         'grade_username' => $uname,
                   9328:                         'grade_domain'   => $udom,
                   9329:                         'grade_courseid' => $env{'request.course.id'},
                   9330:                         'grade_symb'     => $ressymb,
                   9331:                         'CODE'           => $scancode
                   9332:                        );
1.649     raeburn  9333:             if ($bubbles_per_row ne '') {
                   9334:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9335:             }
1.663     raeburn  9336:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9337:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9338:             }
1.554     raeburn  9339:             if (ref($parts) eq 'HASH') {
                   9340:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9341:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9342:                         if ($uselookup) {
                   9343:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9344:                         } else {
                   9345:                             $form{'scantron_questnum_start.'.$part} =
                   9346:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9347:                         }
1.554     raeburn  9348:                         $count++;
                   9349:                     }
                   9350:                 }
                   9351:             }
                   9352:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9353:             return 'ssi_error' if ($ssi_error);
                   9354:             last if (&Apache::loncommon::connection_aborted($r));
                   9355:         }
1.542     raeburn  9356:     }
                   9357:     return;
                   9358: }
                   9359: 
1.157     albertel 9360: sub scantron_upload_scantron_data {
1.767     raeburn  9361:     my ($r,$symb) = @_;
1.565     raeburn  9362:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9363:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9364:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9365:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9366:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9367: 							  'domainid',
1.565     raeburn  9368: 							  'coursename',$dom);
                   9369:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9370:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9371:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9372:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9373:     &js_escape(\$nofile_alert);
1.579     raeburn  9374:     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  9375:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9376:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9377:     function checkUpload(formname) {
                   9378: 	if (formname.upfile.value == "") {
1.579     raeburn  9379: 	    alert("'.$nofile_alert.'");
1.157     albertel 9380: 	    return false;
                   9381: 	}
1.565     raeburn  9382:         if (formname.courseid.value == "") {
1.579     raeburn  9383:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9384:             return false;
                   9385:         }
1.157     albertel 9386: 	formname.submit();
                   9387:     }
1.565     raeburn  9388: 
                   9389:     function ToSyllabus() {
                   9390:         var cdom = '."'$dom'".';
                   9391:         var cnum = document.rules.courseid.value;
                   9392:         if (cdom == "" || cdom == null) {
                   9393:             return;
                   9394:         }
                   9395:         if (cnum == "" || cnum == null) {
                   9396:            return;
                   9397:         }
                   9398:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9399:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9400:         return;
                   9401:     }
                   9402: 
1.754     raeburn  9403:     '.$formatjs.'
1.597     wenzelju 9404: '));
                   9405:     $r->print('
1.648     bisitz   9406: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9407: 
1.492     albertel 9408: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9409: '.$default_form_data.
                   9410:   &Apache::lonhtmlcommon::start_pick_box().
                   9411:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9412:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9413:   &Apache::lonhtmlcommon::row_closure().
                   9414:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9415:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9416:   &Apache::lonhtmlcommon::row_closure().
                   9417:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9418:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9419:   &Apache::lonhtmlcommon::row_closure());
                   9420:     if ($formatoptions) {
                   9421:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9422:                   &Apache::lonhtmlcommon::row_closure());
                   9423:     }
                   9424:     $r->print(
1.565     raeburn  9425:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9426:   '<input type="file" name="upfile" size="50" />'.
                   9427:   &Apache::lonhtmlcommon::row_closure(1).
                   9428:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9429: 
1.492     albertel 9430: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9431: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9432: </form>
1.492     albertel 9433: ');
1.157     albertel 9434:     return '';
                   9435: }
                   9436: 
1.754     raeburn  9437: sub scantron_upload_dataformat {
                   9438:     my ($dom) = @_;
                   9439:     my ($formatoptions,$formattitle,$formatjs);
                   9440:     $formatjs = <<'END';
                   9441: function toggleScantab(form) {
                   9442:    return;
                   9443: }
                   9444: END
                   9445:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9446:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9447:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9448:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9449:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9450:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9451:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9452:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9453:                             my ($onclick,$formatextra,$singleline);
                   9454:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9455:                             my $count = 0;
                   9456:                             foreach my $line (@lines) {
                   9457:                                 next if ($line =~ /^#/);
                   9458:                                 $singleline = $line;
                   9459:                                 $count ++;
                   9460:                             }
                   9461:                             if ($count > 1) {
                   9462:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9463:                                                '<span class="LC_nobreak">'.
                   9464:                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9465:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9466:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9467:                                 $formatjs = <<"END";
1.754     raeburn  9468: function toggleScantab(form) {
                   9469:     var divid = 'bubbletype';
                   9470:     if (document.getElementById(divid)) {
                   9471:         var radioname = 'fileformat';
                   9472:         var num = form.elements[radioname].length;
                   9473:         if (num) {
                   9474:             for (var i=0; i<num; i++) {
                   9475:                 if (form.elements[radioname][i].checked) {
                   9476:                     var chosen = form.elements[radioname][i].value;
                   9477:                     if (chosen == 'dat') {
                   9478:                         document.getElementById(divid).style.display = 'none';
                   9479:                     } else if (chosen == 'csv') {
1.757     raeburn  9480:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9481:                     }
                   9482:                 }
                   9483:             }
                   9484:         }
                   9485:     }
                   9486:     return;
                   9487: }
                   9488: 
                   9489: END
1.756     raeburn  9490:                             } elsif ($count == 1) {
                   9491:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9492:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9493:                             }
                   9494:                             $formattitle = &mt('File format');
                   9495:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9496:                                              &mt('Plain Text (no delimiters)').
                   9497:                                              '</label>'.('&nbsp;'x2).
                   9498:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9499:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9500:                         }
                   9501:                     }
                   9502:                 }
                   9503:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9504:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9505:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9506:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9507:                         $formatoptions = &scantron_scantab();
                   9508:                     }
1.754     raeburn  9509:                 }
                   9510:             }
                   9511:         }
                   9512:     }
                   9513:     return ($formatoptions,$formattitle,$formatjs);
                   9514: }
1.423     albertel 9515: 
1.157     albertel 9516: sub scantron_upload_scantron_data_save {
1.767     raeburn  9517:     my ($r,$symb) = @_;
1.182     albertel 9518:     my $doanotherupload=
                   9519: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9520: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9521: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9522: 	'</form>'."\n";
1.257     albertel 9523:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9524: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9525: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9526:         !&Apache::lonnet::allowed('usc',
                   9527:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9528: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9529: 	unless ($symb) {
1.182     albertel 9530: 	    $r->print($doanotherupload);
                   9531: 	}
1.162     albertel 9532: 	return '';
                   9533:     }
1.257     albertel 9534:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9535:     my $uploadedfile;
1.710     bisitz   9536:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9537:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9538:         $r->print(
                   9539:             &Apache::lonhtmlcommon::confirm_success(
                   9540:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9541:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9542:     } else {
1.754     raeburn  9543:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9544:         my $parser;
                   9545:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9546:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9547:                 my $is_csv;
                   9548:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9549:                 if (@possibles > 1) {
                   9550:                     if ($env{'form.fileformat'} eq 'csv') {
                   9551:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9552:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9553:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9554:                                     $is_csv = 1;
                   9555:                                 }
1.754     raeburn  9556:                             }
                   9557:                         }
                   9558:                     }
                   9559:                 } elsif (@possibles == 1) {
                   9560:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9561:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9562:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9563:                                 $is_csv = 1;
                   9564:                             }
1.754     raeburn  9565:                         }
                   9566:                     }
                   9567:                 }
                   9568:                 if ($is_csv) {
                   9569:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9570:                 }
                   9571:             }
                   9572:         }
                   9573:         my $result =
                   9574:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9575:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9576:         if ($result =~ m{^/uploaded/}) {
                   9577:             $r->print(
                   9578:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9579:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9580:                         (length($env{'form.upfile'})-1),
                   9581:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9582:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9583:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9584:                 my $logname = $uploadedfile;
                   9585:                 $logname =~ s/^scantron_orig_//;
                   9586:                 if ($logname ne '') {
                   9587:                     my $now = time;
                   9588:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9589:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9590:                 }
                   9591:             }
1.567     raeburn  9592:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9593:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9594:         } else {
                   9595:             $r->print(
                   9596:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9597:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9598:                           $result,
1.568     raeburn  9599: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9600: 	}
                   9601:     }
1.174     albertel 9602:     if ($symb) {
1.612     www      9603: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9604:     } else {
1.182     albertel 9605: 	$r->print($doanotherupload);
1.174     albertel 9606:     }
1.157     albertel 9607:     return '';
                   9608: }
                   9609: 
1.567     raeburn  9610: sub validate_uploaded_scantron_file {
1.770     raeburn  9611:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9612: 
1.567     raeburn  9613:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9614:     my @lines;
                   9615:     if ($scanlines ne '-1') {
                   9616:         @lines=split("\n",$scanlines,-1);
                   9617:     }
1.770     raeburn  9618:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9619:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9620:     if ($context eq 'download') {
                   9621:         $priv = 'mgr';
                   9622:     } else {
                   9623:         $priv = 'usc';
                   9624:     }
                   9625:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9626:             (($env{'request.course.id'}) &&
                   9627:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9628:         if ($env{'request.course.sec'} ne '') {
                   9629:             unless (&Apache::lonnet::allowed($priv,
                   9630:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9631:                 unless ($context eq 'download') {
                   9632:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9633:                 }
                   9634:                 return $output;
                   9635:             }
                   9636:             ($checksec,@possibles)=&gradable_sections();
                   9637:         }
                   9638:     }
1.567     raeburn  9639:     if (@lines) {
                   9640:         my (%counts,$max_match_format);
1.710     bisitz   9641:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9642:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9643:         my %idmap = &username_to_idmap($classlist);
                   9644:         foreach my $key (keys(%idmap)) {
                   9645:             my $lckey = lc($key);
                   9646:             $idmap{$lckey} = $idmap{$key};
                   9647:         }
                   9648:         my %unique_formats;
1.754     raeburn  9649:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9650:         foreach my $line (@formatlines) {
                   9651:             chomp($line);
                   9652:             my @config = split(/:/,$line);
                   9653:             my $idstart = $config[5];
                   9654:             my $idlength = $config[6];
                   9655:             if (($idstart ne '') && ($idlength > 0)) {
                   9656:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9657:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9658:                 } else {
                   9659:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9660:                 }
                   9661:             }
                   9662:         }
                   9663:         foreach my $key (keys(%unique_formats)) {
                   9664:             my ($idstart,$idlength) = split(':',$key);
                   9665:             %{$counts{$key}} = (
                   9666:                                'found'   => 0,
                   9667:                                'total'   => 0,
1.770     raeburn  9668:                                'totalanysec' => 0,
                   9669:                                'othersec' => 0,
1.567     raeburn  9670:                               );
                   9671:             foreach my $line (@lines) {
                   9672:                 next if ($line =~ /^#/);
                   9673:                 next if ($line =~ /^[\s\cz]*$/);
                   9674:                 my $id = substr($line,$idstart-1,$idlength);
                   9675:                 $id = lc($id);
                   9676:                 if (exists($idmap{$id})) {
1.770     raeburn  9677:                     if ($checksec ne '') {
                   9678:                         $counts{$key}{'totalanysec'} ++;
                   9679:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9680:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9681:                             if ($stusec ne $checksec) {
                   9682:                                 if (@possibles) {
                   9683:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9684:                                         $counts{$key}{'othersec'} ++;
                   9685:                                         next;
                   9686:                                     }
                   9687:                                 } else {
                   9688:                                     $counts{$key}{'othersec'} ++;
                   9689:                                     next;
                   9690:                                 }
                   9691:                             }
                   9692:                         }
                   9693:                     }
1.567     raeburn  9694:                     $counts{$key}{'found'} ++;
                   9695:                 }
                   9696:                 $counts{$key}{'total'} ++;
                   9697:             }
                   9698:             if ($counts{$key}{'total'}) {
                   9699:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9700:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9701:                     $max_match_pct = $percent_match;
                   9702:                     $max_match_format = $key;
1.710     bisitz   9703:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9704:                     $max_match_count = $counts{$key}{'total'};
                   9705:                 }
                   9706:             }
                   9707:         }
1.770     raeburn  9708:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9709:             my $format_descs;
                   9710:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9711:             for (my $i=0; $i<$numwithformat; $i++) {
                   9712:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9713:                 if ($i<$numwithformat-2) {
                   9714:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9715:                 } elsif ($i==$numwithformat-2) {
                   9716:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9717:                 } elsif ($i==$numwithformat-1) {
                   9718:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9719:                 }
                   9720:             }
                   9721:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9722:             $output .= '<br />';
                   9723:             if ($found_match_count == $max_match_count) {
                   9724:                 # 100% matching entries
                   9725:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9726:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9727:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9728:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9729:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9730:                     ' in the file (for the format defined for [_3]).',
                   9731:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9732:             } else {
                   9733:                 # Not all entries matching? -> Show warning and additional info
                   9734:                 $output .=
                   9735:                     &Apache::lonhtmlcommon::confirm_success(
                   9736:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9737:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9738:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9739:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9740:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9741:                         ' in the file (for the format defined for [_3]).',
                   9742:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9743:                     '<p class="LC_info">'.
                   9744:                     &mt('A low percentage of matches results from one of the following:').
                   9745:                     '</p><ul>'.
                   9746:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9747:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9748:                                '<i>'.$cdom.'</i>').'</li>'.
                   9749:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9750:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9751:                     '</ul>';
                   9752:             }
1.770     raeburn  9753:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9754:                 if ($counts{$max_match_format}{'othersec'}) {
                   9755:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9756:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9757:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9758:                     &js_escape(\$confirmdel);
                   9759:                     $output .= '<p class="LC_warning">'.
                   9760:                                &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',
                   9761:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9762:                                '<br />'.
                   9763:                                &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>').
                   9764:                                '</p><p>'.
                   9765:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9766:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9767:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9768:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9769:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9770:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9771:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9772:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9773:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9774:                                '</form></p>';
                   9775:                 }
                   9776:             }
1.567     raeburn  9777:         }
1.770     raeburn  9778:         if (($context eq 'download') && ($checksec ne '')) {
                   9779:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9780:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9781:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9782:             }
                   9783:         } 
                   9784:     } elsif ($context ne 'download') {
1.710     bisitz   9785:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9786:     }
                   9787:     return $output;
                   9788: }
                   9789: 
1.770     raeburn  9790: sub gradable_sections {
                   9791:     my $checksec = $env{'request.course.sec'};
                   9792:     my @oksecs;
                   9793:     if ($checksec) {
                   9794:         my %availablesecs = &sections_grade_privs();
                   9795:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9796:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9797:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9798:                     push(@oksecs,$sec);
                   9799:                 }
                   9800:             }
                   9801:             if (grep(/^all$/,@oksecs)) {
                   9802:                 undef($checksec);
                   9803:             }
                   9804:         }
                   9805:     }
                   9806:     return($checksec,@oksecs);
                   9807: }
                   9808: 
                   9809: sub sections_grade_privs {
                   9810:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9811:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9812:     my %availablesecs = (
                   9813:                           mgr => [],
                   9814:                           vgr => [],
                   9815:                           usc => [],
                   9816:                         );
                   9817:     my $ccrole = 'cc';
                   9818:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9819:         $ccrole = 'co';
                   9820:     }
                   9821:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9822:                                                      'userroles',['active'],
                   9823:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9824:     my $crsid = $cnum.':'.$cdom;
                   9825:     foreach my $item (keys(%crsroleshash)) {
                   9826:         next unless ($item =~ /^$crsid\:/);
                   9827:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9828:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9829:         if ($sec ne '') {
                   9830:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9831:         }
                   9832:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9833:             foreach my $priv ('mgr','vgr','usc') { 
                   9834:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9835:                     if ($sec eq '') {
                   9836:                         $availablesecs{$priv} = ['all'];
                   9837:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9838:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9839:                             push(@{$availablesecs{$priv}},$sec);
                   9840:                         }
                   9841:                     }
                   9842:                 }
                   9843:             }
                   9844:         } elsif ($role =~ m{^cr/}) {
                   9845:             foreach my $priv ('mgr','vgr','usc') {
                   9846:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9847:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9848:                         if ($sec eq '') {
                   9849:                             $availablesecs{$priv} = ['all'];
                   9850:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9851:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9852:                                 push(@{$availablesecs{$priv}},$sec);
                   9853:                             }
                   9854:                         }
                   9855:                     }
                   9856:                 }
                   9857:             }
                   9858:         }
                   9859:     }
                   9860:     return %availablesecs;
                   9861: }
                   9862: 
                   9863: sub scantron_upload_delete {
                   9864:     my ($r,$symb) = @_;
                   9865:     my $filename = $env{'form.uploadedfile'};
                   9866:     if ($filename =~ /^scantron_orig_/) {
                   9867:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9868:             &Apache::lonnet::allowed('usc',
                   9869:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9870:             &Apache::lonnet::allowed('usc',
                   9871:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9872:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9873:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9874:             if ($retrieval eq '-1') {
                   9875:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9876:                           &mt('File requested for deletion not found.'));
                   9877:             } else {
                   9878:                 $filename =~ s/^scantron_orig_//;
                   9879:                 if ($filename ne '') {
                   9880:                     my ($is_valid,$numleft);
                   9881:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9882:                     if (keys(%info)) {
                   9883:                         if (ref($info{$filename}) eq 'HASH') {
                   9884:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9885:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9886:                                     $is_valid = 1;
                   9887:                                     delete($info{$filename}{$timestamp}); 
                   9888:                                 }
                   9889:                             }
                   9890:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9891:                         }
                   9892:                     }
                   9893:                     if ($is_valid) {
                   9894:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9895:                         if ($result eq 'ok') {
                   9896:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9897:                             if ($numleft) {
                   9898:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9899:                             } else {
                   9900:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9901:                             }
                   9902:                         } else {
                   9903:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9904:                                       &mt('Result was [_1]',$result));
                   9905:                         }
                   9906:                     } else {
                   9907:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9908:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9909:                     }
                   9910:                 } else {
                   9911:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9912:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9913:                 }
                   9914:             }
                   9915:         } else {
                   9916:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9917:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9918:         }
                   9919:     } else {
                   9920:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9921:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9922:     }
                   9923:     return;
                   9924: }
                   9925: 
1.202     albertel 9926: sub valid_file {
                   9927:     my ($requested_file)=@_;
                   9928:     foreach my $filename (sort(&scantron_filenames())) {
                   9929: 	if ($requested_file eq $filename) { return 1; }
                   9930:     }
                   9931:     return 0;
                   9932: }
                   9933: 
                   9934: sub scantron_download_scantron_data {
1.767     raeburn  9935:     my ($r,$symb) = @_;
1.608     www      9936:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9938:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9939:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9940:     if (! &valid_file($file)) {
1.492     albertel 9941: 	$r->print('
1.202     albertel 9942: 	<p>
1.686     bisitz   9943: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9944:         </p>
1.492     albertel 9945: ');
1.202     albertel 9946: 	return;
                   9947:     }
1.770     raeburn  9948:     my (%uploader,$is_owner,%counts,$percent);
                   9949:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   9950:     if (ref($uploader{$file}) eq 'HASH') {
                   9951:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   9952:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9953:                 $is_owner = 1;
                   9954:                 last;
                   9955:             }
                   9956:         }
                   9957:     }
                   9958:     unless ($is_owner) {
                   9959:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   9960:         if ($counts{'totalanysec'}) {
                   9961:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   9962:             if ($percent_othersec >= 10) {
                   9963:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   9964:                 $r->print('<p class="LC_warning">'.
                   9965:                           &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).
                   9966:                           '</p>');
                   9967:                 return;
                   9968:             }
                   9969:         }
                   9970:     }
1.202     albertel 9971:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9972:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9973:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9974:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9975:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9976:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9977:     $r->print('
1.202     albertel 9978:     <p>
1.723     raeburn  9979: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9980: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9981:     </p>
                   9982:     <p>
1.492     albertel 9983: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9984: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9985:     </p>
                   9986:     <p>
1.492     albertel 9987: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9988: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9989:     </p>
1.492     albertel 9990: ');
1.202     albertel 9991:     return '';
                   9992: }
1.157     albertel 9993: 
1.523     raeburn  9994: sub checkscantron_results {
1.608     www      9995:     my ($r,$symb) = @_;
1.523     raeburn  9996:     if (!$symb) {return '';}
                   9997:     my $cid = $env{'request.course.id'};
1.755     raeburn  9998:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9999:     my $numletts = scalar(keys(%lettdig));
                   10000:     my $cnum = $env{'course.'.$cid.'.num'};
                   10001:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10002:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10003:     my %record;
                   10004:     my %scantron_config =
1.754     raeburn  10005:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10006:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10007:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10008:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10009:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10010:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10011:     unless (ref($navmap)) {
                   10012:         $r->print(&navmap_errormsg());
                   10013:         return '';
                   10014:     }
1.523     raeburn  10015:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10016:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10017:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10018:     if (ref($map)) { 
                   10019:         $randomorder=$map->randomorder();
1.689     raeburn  10020:         $randompick=$map->randompick();
1.677     raeburn  10021:     }
1.557     raeburn  10022:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10023:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10024:     if ($nav_error) {
                   10025:         $r->print(&navmap_errormsg());
                   10026:         return '';
1.678     raeburn  10027:     }
1.673     raeburn  10028:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10029:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10030:     my ($uname,$udom);
1.523     raeburn  10031:     my (%scandata,%lastname,%bylast);
                   10032:     $r->print('
                   10033: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10034: 
                   10035:     my @delayqueue;
                   10036:     my %completedstudents;
                   10037: 
1.691     raeburn  10038:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10039:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10040:     my ($username,$domain,$started);
1.649     raeburn  10041:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10042:     if ($nav_error) {
                   10043:         $r->print(&navmap_errormsg());
                   10044:         return '';
                   10045:     }
1.523     raeburn  10046: 
1.667     www      10047:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10048:     my $start=&Time::HiRes::time();
                   10049:     my $i=-1;
                   10050: 
                   10051:     while ($i<$scanlines->{'count'}) {
                   10052:         ($username,$domain,$uname)=('','','');
                   10053:         $i++;
                   10054:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10055:         if ($line=~/^[\s\cz]*$/) { next; }
                   10056:         if ($started) {
1.667     www      10057:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10058:         }
                   10059:         $started=1;
                   10060:         my $scan_record=
                   10061:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10062:                                                      $scan_data);
1.693     raeburn  10063:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10064:                                               \%idmap,$i)) {
1.523     raeburn  10065:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10066:                                 'Unable to find a student that matches',1);
                   10067:             next;
                   10068:         }
                   10069:         if (exists $completedstudents{$uname}) {
                   10070:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10071:                                 'Student '.$uname.' has multiple sheets',2);
                   10072:             next;
                   10073:         }
                   10074:         my $pid = $scan_record->{'scantron.ID'};
                   10075:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10076:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10077:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10078:         my $user = $uname.':'.$usec;
1.523     raeburn  10079:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10080: 
1.678     raeburn  10081:         my $scancode;
1.677     raeburn  10082:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10083:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10084:             $scancode = $scan_record->{'scantron.CODE'};
                   10085:         } else {
                   10086:             $scancode = '';
                   10087:         }
                   10088: 
                   10089:         my @mapresources = @resources;
1.691     raeburn  10090:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10091:         my %respnumlookup=();
                   10092:         my %startline=();
1.689     raeburn  10093:         if ($randomorder || $randompick) {
1.678     raeburn  10094:             @mapresources =
1.691     raeburn  10095:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10096:                              \%orderedforcode);
                   10097:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10098:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10099:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10100:                                              \%respnumlookup,\%startline);
                   10101:             if ($randompick && $total) {
                   10102:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10103:             }
1.677     raeburn  10104:         }
1.691     raeburn  10105:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10106:         chomp($scandata{$pid});
                   10107:         $scandata{$pid} =~ s/\r$//;
                   10108: 
1.523     raeburn  10109:         my $counter = -1;
1.677     raeburn  10110:         foreach my $resource (@mapresources) {
1.557     raeburn  10111:             my $parts;
1.554     raeburn  10112:             my $ressymb = $resource->symb();
1.557     raeburn  10113:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10114:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10115:                 my $currcode;
                   10116:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10117:                     $currcode = $scancode;
                   10118:                 }
1.557     raeburn  10119:                 (my $analysis,$parts) =
1.672     raeburn  10120:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10121:                                               $username,$domain,undef,
1.741     raeburn  10122:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10123:             } else {
                   10124:                 $parts = $grader_partids_by_symb{$ressymb};
                   10125:             }
1.542     raeburn  10126:             ($counter,my $recording) =
                   10127:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10128:                                          $scandata{$pid},$parts,
1.691     raeburn  10129:                                          \%scantron_config,\%lettdig,$numletts,
                   10130:                                          $randomorder,$randompick,
                   10131:                                          \%respnumlookup,\%startline);
1.542     raeburn  10132:             $record{$pid} .= $recording;
1.523     raeburn  10133:         }
                   10134:     }
                   10135:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10136:     $r->print('<br />');
                   10137:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10138:     $passed = 0;
                   10139:     $failed = 0;
                   10140:     $numstudents = 0;
                   10141:     foreach my $last (sort(keys(%bylast))) {
                   10142:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10143:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10144:                 my $showscandata = $scandata{$pid};
                   10145:                 my $showrecord = $record{$pid};
                   10146:                 $showscandata =~ s/\s/&nbsp;/g;
                   10147:                 $showrecord =~ s/\s/&nbsp;/g;
                   10148:                 if ($scandata{$pid} eq $record{$pid}) {
                   10149:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10150:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10151: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10152: '</tr>'."\n".
                   10153: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10154: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10155:                     $passed ++;
                   10156:                 } else {
                   10157:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10158:                     $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  10159: '</tr>'."\n".
                   10160: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10161: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10162: '</tr>'."\n";
                   10163:                     $failed ++;
                   10164:                 }
                   10165:                 $numstudents ++;
                   10166:             }
                   10167:         }
                   10168:     }
1.648     bisitz   10169:     $r->print(
                   10170:         '<p>'
                   10171:        .&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).',
                   10172:             '<b>',
                   10173:             $numstudents,
                   10174:             '</b>',
                   10175:             $env{'form.scantron_maxbubble'})
                   10176:        .'</p>'
                   10177:     );
1.682     raeburn  10178:     $r->print('<p>'
1.683     raeburn  10179:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10180:              .'<br />'
                   10181:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10182:              .'</p>'
                   10183:     );
1.523     raeburn  10184:     if ($passed) {
1.572     www      10185:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10186:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10187:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10188:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10189:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10190:                  $okstudents."\n".
                   10191:                  &Apache::loncommon::end_data_table().'<br />');
                   10192:     }
                   10193:     if ($failed) {
1.572     www      10194:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10195:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10196:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10197:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10198:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10199:                  $badstudents."\n".
                   10200:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10201:                  &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  10202:     }
1.614     www      10203:     $r->print('</form><br />');
1.523     raeburn  10204:     return;
                   10205: }
                   10206: 
1.542     raeburn  10207: sub verify_scantron_grading {
1.554     raeburn  10208:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10209:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10210:         $respnumlookup,$startline) = @_;
1.542     raeburn  10211:     my ($record,%expected,%startpos);
                   10212:     return ($counter,$record) if (!ref($resource));
                   10213:     return ($counter,$record) if (!$resource->is_problem());
                   10214:     my $symb = $resource->symb();
1.554     raeburn  10215:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10216:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10217:         $counter ++;
                   10218:         $expected{$part_id} = 0;
1.691     raeburn  10219:         my $respnum = $counter;
                   10220:         if ($randomorder || $randompick) {
                   10221:             $respnum = $respnumlookup->{$counter};
                   10222:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10223:         } else {
                   10224:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10225:         }
                   10226:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10227:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10228:             foreach my $item (@sub_lines) {
                   10229:                 $expected{$part_id} += $item;
                   10230:             }
                   10231:         } else {
1.691     raeburn  10232:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10233:         }
                   10234:     }
                   10235:     if ($symb) {
                   10236:         my %recorded;
                   10237:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10238:         if ($returnhash{'version'}) {
                   10239:             my %lasthash=();
                   10240:             my $version;
                   10241:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10242:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10243:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10244:                 }
                   10245:             }
                   10246:             foreach my $key (keys(%lasthash)) {
                   10247:                 if ($key =~ /\.scantron$/) {
                   10248:                     my $value = &unescape($lasthash{$key});
                   10249:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10250:                     if ($value eq '') {
                   10251:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10252:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10253:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10254:                             }
                   10255:                         }
                   10256:                     } else {
                   10257:                         my @tocheck;
                   10258:                         my @items = split(//,$value);
                   10259:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10260:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10261:                             if (@items < $expected{$part_id}) {
                   10262:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10263:                                 my @singles = split(//,$fragment);
                   10264:                                 foreach my $pos (@singles) {
                   10265:                                     if ($pos eq ' ') {
                   10266:                                         push(@tocheck,$pos);
                   10267:                                     } else {
                   10268:                                         my $next = shift(@items);
                   10269:                                         push(@tocheck,$next);
                   10270:                                     }
                   10271:                                 }
                   10272:                             } else {
                   10273:                                 @tocheck = @items;
                   10274:                             }
                   10275:                             foreach my $letter (@tocheck) {
                   10276:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10277:                                     if ($letter !~ /^[A-J]$/) {
                   10278:                                         $letter = $scantron_config->{'Qoff'};
                   10279:                                     }
                   10280:                                     $recorded{$part_id} .= $letter;
                   10281:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10282:                                     my $digit;
                   10283:                                     if ($letter !~ /^[A-J]$/) {
                   10284:                                         $digit = $scantron_config->{'Qoff'};
                   10285:                                     } else {
                   10286:                                         $digit = $lettdig->{$letter};
                   10287:                                     }
                   10288:                                     $recorded{$part_id} .= $digit;
                   10289:                                 }
                   10290:                             }
                   10291:                         } else {
                   10292:                             @tocheck = @items;
                   10293:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10294:                                 my $curr_sub = shift(@tocheck);
                   10295:                                 my $digit;
                   10296:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10297:                                     $digit = $lettdig->{$curr_sub}-1;
                   10298:                                 }
                   10299:                                 if ($curr_sub eq 'J') {
                   10300:                                     $digit += scalar($numletts);
                   10301:                                 }
                   10302:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10303:                                     if ($j == $digit) {
                   10304:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10305:                                     } else {
                   10306:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10307:                                     }
                   10308:                                 }
                   10309:                             }
                   10310:                         }
                   10311:                     }
                   10312:                 }
                   10313:             }
                   10314:         }
1.554     raeburn  10315:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10316:             if ($recorded{$part_id} eq '') {
                   10317:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10318:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10319:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10320:                     }
                   10321:                 }
                   10322:             }
                   10323:             $record .= $recorded{$part_id};
                   10324:         }
                   10325:     }
                   10326:     return ($counter,$record);
                   10327: }
                   10328: 
1.75      albertel 10329: #-------- end of section for handling grading scantron forms -------
                   10330: #
                   10331: #-------------------------------------------------------------------
                   10332: 
1.72      ng       10333: #-------------------------- Menu interface -------------------------
                   10334: #
1.614     www      10335: #--- Href with symb and command ---
                   10336: 
                   10337: sub href_symb_cmd {
                   10338:     my ($symb,$cmd)=@_;
1.669     raeburn  10339:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10340: }
                   10341: 
1.443     banghart 10342: sub grading_menu {
1.608     www      10343:     my ($request,$symb) = @_;
1.443     banghart 10344:     if (!$symb) {return '';}
                   10345: 
                   10346:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10347:                   'command'=>'individual');
1.538     schulted 10348:     
1.598     www      10349:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10350: 
                   10351:     $fields{'command'}='ungraded';
                   10352:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10353: 
                   10354:     $fields{'command'}='table';
                   10355:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10356: 
                   10357:     $fields{'command'}='all_for_one';
                   10358:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10359: 
1.621     www      10360:     $fields{'command'}='downloadfilesselect';
                   10361:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10362: 
1.443     banghart 10363:     $fields{'command'} = 'csvform';
1.538     schulted 10364:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10365:     
1.443     banghart 10366:     $fields{'command'} = 'processclicker';
1.538     schulted 10367:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10368:     
1.443     banghart 10369:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10370:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10371: 
                   10372:     $fields{'command'} = 'initialverifyreceipt';
                   10373:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10374:     
1.598     www      10375:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10376:             items =>[
1.598     www      10377:                         {	linktext => 'Select individual students to grade',
                   10378:                     		url => $url1a,
1.538     schulted 10379:                     		permission => 'F',
1.636     wenzelju 10380:                     		icon => 'grade_students.png',
1.598     www      10381:                     		linktitle => 'Grade current resource for a selection of students.'
                   10382:                         }, 
1.764     raeburn  10383:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10384:                                 url => $url1b,
                   10385:                                 permission => 'F',
1.636     wenzelju 10386:                                 icon => 'ungrade_sub.png',
1.598     www      10387:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10388:                         },
1.598     www      10389: 
                   10390:                         {       linktext => 'Grading table',
                   10391:                                 url => $url1c,
                   10392:                                 permission => 'F',
1.636     wenzelju 10393:                                 icon => 'grading_table.png',
1.598     www      10394:                                 linktitle => 'Grade current resource for all students.'
                   10395:                         },
1.615     www      10396:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10397:                                 url => $url1d,
                   10398:                                 permission => 'F',
1.636     wenzelju 10399:                                 icon => 'grade_PageFolder.png',
1.598     www      10400:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10401:                         },
                   10402:                         {       linktext => 'Download submissions',
                   10403:                                 url => $url1e,
                   10404:                                 permission => 'F',
1.636     wenzelju 10405:                                 icon => 'download_sub.png',
1.621     www      10406:                                 linktitle => 'Download all students submissions.'
1.598     www      10407:                         }]},
                   10408:                          { categorytitle=>'Automated Grading',
                   10409:                items =>[
                   10410: 
1.538     schulted 10411:                 	    {	linktext => 'Upload Scores',
                   10412:                     		url => $url2,
                   10413:                     		permission => 'F',
                   10414:                     		icon => 'uploadscores.png',
                   10415:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10416:                 	    },
                   10417:                 	    {	linktext => 'Process Clicker',
                   10418:                     		url => $url3,
                   10419:                     		permission => 'F',
                   10420:                     		icon => 'addClickerInfoFile.png',
                   10421:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10422:                 	    },
1.587     raeburn  10423:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10424:                     		url => $url4,
                   10425:                     		permission => 'F',
1.636     wenzelju 10426:                     		icon => 'bubblesheet.png',
1.648     bisitz   10427:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10428:                 	    },
1.616     www      10429:                             {   linktext => 'Verify Receipt Number',
1.602     www      10430:                                 url => $url5,
                   10431:                                 permission => 'F',
1.636     wenzelju 10432:                                 icon => 'receipt_number.png',
1.602     www      10433:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10434:                             }
                   10435: 
1.538     schulted 10436:                     ]
                   10437:             });
                   10438: 
1.443     banghart 10439:     # Create the menu
                   10440:     my $Str;
1.445     banghart 10441:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10442:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10443:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10444: 
1.602     www      10445:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10446:     return $Str;    
                   10447: }
                   10448: 
1.598     www      10449: sub ungraded {
                   10450:     my ($request)=@_;
                   10451:     &submit_options($request);
                   10452: }
                   10453: 
1.599     www      10454: sub submit_options_sequence {
1.608     www      10455:     my ($request,$symb) = @_;
1.599     www      10456:     if (!$symb) {return '';}
1.600     www      10457:     &commonJSfunctions($request);
                   10458:     my $result;
1.599     www      10459: 
1.600     www      10460:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10461:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10462:     $result.=&selectfield(0).
1.601     www      10463:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10464:             <div>
                   10465:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10466:             </div>
                   10467:         </div>
                   10468:   </form>';
                   10469:     return $result;
                   10470: }
                   10471: 
                   10472: sub submit_options_table {
1.608     www      10473:     my ($request,$symb) = @_;
1.600     www      10474:     if (!$symb) {return '';}
1.599     www      10475:     &commonJSfunctions($request);
1.746     raeburn  10476:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10477:     my $result;
                   10478: 
                   10479:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10480:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10481: 
1.745     raeburn  10482:     $result.=&selectfield(1,$is_tool).
1.601     www      10483:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10484:             <div>
                   10485:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10486:             </div>
                   10487:         </div>
                   10488:   </form>';
                   10489:     return $result;
                   10490: }
1.443     banghart 10491: 
1.621     www      10492: sub submit_options_download {
                   10493:     my ($request,$symb) = @_;
                   10494:     if (!$symb) {return '';}
                   10495: 
1.773     raeburn  10496:     my $res_error;
                   10497:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10498:         &response_type($symb,\$res_error);
                   10499:     if ($res_error) {
                   10500:         $request->print(&mt('An error occurred retrieving response types'));
                   10501:         return;
                   10502:     }
                   10503:     unless ($numessay) {
                   10504:         $request->print(&mt('No essayresponse items found'));
                   10505:         return;
                   10506:     }
                   10507:     my $table;
                   10508:     if (ref($partlist) eq 'ARRAY') {
                   10509:         if (scalar(@$partlist) > 1 ) {
                   10510:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
                   10511:         }
                   10512:     }
                   10513: 
1.746     raeburn  10514:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10515:     &commonJSfunctions($request);
                   10516: 
                   10517:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773     raeburn  10518:                $table."\n".
                   10519:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10520:     $result.='
                   10521: <h2>
1.750     raeburn  10522:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10523: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10524:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10525:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10526:             </div>
                   10527:           </div>
1.600     www      10528: 
                   10529: 
1.621     www      10530:   </form>';
                   10531:     return $result;
                   10532: }
                   10533: 
1.443     banghart 10534: #--- Displays the submissions first page -------
                   10535: sub submit_options {
1.608     www      10536:     my ($request,$symb) = @_;
1.72      ng       10537:     if (!$symb) {return '';}
                   10538: 
1.746     raeburn  10539:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10540:     &commonJSfunctions($request);
1.473     albertel 10541:     my $result;
1.533     bisitz   10542: 
1.72      ng       10543:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10544: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10545:     $result.=&selectfield(1,$is_tool).'
1.601     www      10546:                 <input type="hidden" name="command" value="submission" /> 
                   10547: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10548:             </div>
                   10549:           </div>
                   10550:   </form>';
                   10551:     return $result;
                   10552: }
1.533     bisitz   10553: 
1.601     www      10554: sub selectfield {
1.745     raeburn  10555:    my ($full,$is_tool)=@_;
                   10556:    my %options;
                   10557:    if ($is_tool) {
                   10558:        %options =
                   10559:            (&transtatus_options,
                   10560:             'select_form_order' => ['yes','incorrect','all']);
                   10561:    } else {
                   10562:        %options = 
                   10563:            (&substatus_options,
                   10564:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10565:    }
1.601     www      10566:    my $result='<div class="LC_columnSection">
1.537     harmsja  10567:   
1.533     bisitz   10568:     <fieldset>
                   10569:       <legend>
                   10570:        '.&mt('Sections').'
                   10571:       </legend>
1.601     www      10572:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10573:     </fieldset>
1.537     harmsja  10574:   
1.533     bisitz   10575:     <fieldset>
                   10576:       <legend>
                   10577:         '.&mt('Groups').'
                   10578:       </legend>
                   10579:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10580:     </fieldset>
1.537     harmsja  10581:   
1.533     bisitz   10582:     <fieldset>
                   10583:       <legend>
                   10584:         '.&mt('Access Status').'
                   10585:       </legend>
1.601     www      10586:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10587:     </fieldset>';
                   10588:     if ($full) {
1.745     raeburn  10589:         my $heading = &mt('Submission Status');
                   10590:         if ($is_tool) {
                   10591:             $heading = &mt('Transaction Status');
                   10592:         }
                   10593:         $result.='
1.533     bisitz   10594:     <fieldset>
                   10595:       <legend>
1.745     raeburn  10596:         '.$heading.'
1.601     www      10597:       </legend>'.
1.635     raeburn  10598:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10599:    '</fieldset>';
                   10600:     }
                   10601:     $result.='</div><br />';
1.44      ng       10602:     return $result;
1.2       albertel 10603: }
                   10604: 
1.738     raeburn  10605: sub substatus_options {
                   10606:     return &Apache::lonlocal::texthash(
                   10607:                                       'yes'       => 'with submissions',
                   10608:                                       'queued'    => 'in grading queue',
                   10609:                                       'graded'    => 'with ungraded submissions',
                   10610:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10611:                                       'all'       => 'with any status',
                   10612:                                       );
1.738     raeburn  10613: }
                   10614: 
1.745     raeburn  10615: sub transtatus_options {
                   10616:     return &Apache::lonlocal::texthash(
                   10617:                                        'yes'       => 'with score transactions',
                   10618:                                        'incorrect' => 'with less than full credit',
                   10619:                                        'all'       => 'with any status',
                   10620:                                       );
                   10621: }
                   10622: 
1.285     albertel 10623: sub reset_perm {
                   10624:     undef(%perm);
                   10625: }
                   10626: 
                   10627: sub init_perm {
                   10628:     &reset_perm();
1.770     raeburn  10629:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10630: 
                   10631: 	my $scope = $env{'request.course.id'};
                   10632: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10633: 
                   10634: 	    $scope .= '/'.$env{'request.course.sec'};
                   10635: 	    if ( $perm{$test_perm}=
                   10636: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10637: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10638: 	    } else {
                   10639: 		delete($perm{$test_perm});
                   10640: 	    }
1.285     albertel 10641: 	}
                   10642:     }
                   10643: }
                   10644: 
1.674     raeburn  10645: sub init_old_essays {
                   10646:     my ($symb,$apath,$adom,$aname) = @_;
                   10647:     if ($symb ne '') {
                   10648:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10649:         if (keys(%essays) > 0) {
                   10650:             $old_essays{$symb} = \%essays;
                   10651:         }
                   10652:     }
                   10653:     return;
                   10654: }
                   10655: 
                   10656: sub reset_old_essays {
                   10657:     undef(%old_essays);
                   10658: }
                   10659: 
1.400     www      10660: sub gather_clicker_ids {
1.408     albertel 10661:     my %clicker_ids;
1.400     www      10662: 
                   10663:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10664: 
                   10665:     # Set up a couple variables.
1.407     albertel 10666:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10667:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10668:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10669: 
1.407     albertel 10670:     foreach my $student (keys(%$classlist)) {
1.438     www      10671:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10672:         my $username = $classlist->{$student}->[$username_idx];
                   10673:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10674:         my $clickers =
1.408     albertel 10675: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10676:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10677:             $id=~s/^[\#0]+//;
1.421     www      10678:             $id=~s/[\-\:]//g;
1.407     albertel 10679:             if (exists($clicker_ids{$id})) {
1.408     albertel 10680: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10681:             } else {
1.408     albertel 10682: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10683:             }
                   10684:         }
                   10685:     }
1.407     albertel 10686:     return %clicker_ids;
1.400     www      10687: }
                   10688: 
1.402     www      10689: sub gather_adv_clicker_ids {
1.408     albertel 10690:     my %clicker_ids;
1.402     www      10691:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10692:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10693:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10694:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10695:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10696:             my ($puname,$pudom)=split(/\:/,$person);
                   10697:             my $clickers =
1.408     albertel 10698: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10699:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10700: 		$id=~s/^[\#0]+//;
1.421     www      10701:                 $id=~s/[\-\:]//g;
1.408     albertel 10702: 		if (exists($clicker_ids{$id})) {
                   10703: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10704: 		} else {
                   10705: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10706: 		}
1.405     www      10707:             }
1.402     www      10708:         }
                   10709:     }
1.407     albertel 10710:     return %clicker_ids;
1.402     www      10711: }
                   10712: 
1.413     www      10713: sub clicker_grading_parameters {
                   10714:     return ('gradingmechanism' => 'scalar',
                   10715:             'upfiletype' => 'scalar',
                   10716:             'specificid' => 'scalar',
                   10717:             'pcorrect' => 'scalar',
                   10718:             'pincorrect' => 'scalar');
                   10719: }
                   10720: 
1.400     www      10721: sub process_clicker {
1.608     www      10722:     my ($r,$symb)=@_;
1.400     www      10723:     if (!$symb) {return '';}
                   10724:     my $result=&checkforfile_js();
1.632     www      10725:     $result.=&Apache::loncommon::start_data_table().
                   10726:              &Apache::loncommon::start_data_table_header_row().
                   10727:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10728:              &Apache::loncommon::end_data_table_header_row().
                   10729:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10730: # Attempt to restore parameters from last session, set defaults if not present
                   10731:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10732:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10733:                                                  \%Saveable_Parameters);
                   10734:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10735:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10736:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10737:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10738: 
                   10739:     my %checked;
1.521     www      10740:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10741:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10742:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10743:        }
                   10744:     }
                   10745: 
1.632     www      10746:     my $upload=&mt("Evaluate File");
1.400     www      10747:     my $type=&mt("Type");
1.402     www      10748:     my $attendance=&mt("Award points just for participation");
                   10749:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10750:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10751:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10752:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10753:     my $pcorrect=&mt("Percentage points for correct solution");
                   10754:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10755:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10756: 						   {'iclicker' => 'i>clicker',
1.666     www      10757:                                                     'interwrite' => 'interwrite PRS',
                   10758:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10759:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10760:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10761: function sanitycheck() {
                   10762: // Accept only integer percentages
                   10763:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10764:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10765: // Find out grading choice
                   10766:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10767:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10768:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10769:       }
                   10770:    }
                   10771: // By default, new choice equals user selection
                   10772:    newgradingchoice=gradingchoice;
                   10773: // Not good to give more points for false answers than correct ones
                   10774:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10775:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10776:    }
                   10777: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10778:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10779:       document.forms.gradesupload.pcorrect.value=100;
                   10780:       document.forms.gradesupload.pincorrect.value=100;
                   10781:    }
                   10782: // If the values are different, cannot be attendance only
                   10783:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10784:        (gradingchoice=='attendance')) {
                   10785:        newgradingchoice='personnel';
                   10786:    }
                   10787: // Change grading choice to new one
                   10788:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10789:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10790:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10791:       } else {
                   10792:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10793:       }
                   10794:    }
                   10795: // Remember the old state
                   10796:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10797: }
1.597     wenzelju 10798: ENDUPFORM
                   10799:     $result.= <<ENDUPFORM;
1.400     www      10800: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10801: <input type="hidden" name="symb" value="$symb" />
                   10802: <input type="hidden" name="command" value="processclickerfile" />
                   10803: <input type="file" name="upfile" size="50" />
                   10804: <br /><label>$type: $selectform</label>
1.632     www      10805: ENDUPFORM
                   10806:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10807:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10808:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10809: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10810: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10811: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10812: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10813: <br />&nbsp;&nbsp;&nbsp;
                   10814: <input type="text" name="givenanswer" size="50" />
1.413     www      10815: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10816: ENDGRADINGFORM
1.766     raeburn  10817:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10818:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10819:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10820: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10821: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10822: </form>
1.632     www      10823: ENDPERCFORM
                   10824:     $result.='</td>'.
                   10825:              &Apache::loncommon::end_data_table_row().
                   10826:              &Apache::loncommon::end_data_table();
1.400     www      10827:     return $result;
                   10828: }
                   10829: 
                   10830: sub process_clicker_file {
1.766     raeburn  10831:     my ($r,$symb) = @_;
1.400     www      10832:     if (!$symb) {return '';}
1.413     www      10833: 
                   10834:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10835:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10836:                                               \%Saveable_Parameters);
1.598     www      10837:     my $result='';
1.404     www      10838:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10839: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10840: 	return $result;
1.404     www      10841:     }
1.522     www      10842:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10843:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10844:         return $result;
1.521     www      10845:     }
1.522     www      10846:     my $foundgiven=0;
1.521     www      10847:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10848:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10849:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10850:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10851:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10852:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10853:         $foundgiven=$#answers+1;
1.521     www      10854:     }
1.407     albertel 10855:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10856:     my %correct_ids;
1.404     www      10857:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10858: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10859:     }
                   10860:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10861: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10862: 	   $correct_id=~tr/a-z/A-Z/;
                   10863: 	   $correct_id=~s/\s//gs;
                   10864: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10865:            $correct_id=~s/[\-\:]//g;
1.414     www      10866:            if ($correct_id) {
                   10867: 	      $correct_ids{$correct_id}='specified';
                   10868:            }
                   10869:         }
1.400     www      10870:     }
1.404     www      10871:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10872: 	$result.=&mt('Score based on attendance only');
1.521     www      10873:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10874:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10875:     } else {
1.408     albertel 10876: 	my $number=0;
1.411     www      10877: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10878: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10879: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10880: 	    if ($correct_ids{$id} eq 'specified') {
                   10881: 		$result.=&mt('specified');
                   10882: 	    } else {
                   10883: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10884: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10885: 	    }
                   10886: 	    $number++;
                   10887: 	}
1.411     www      10888:         $result.="</p>\n";
1.710     bisitz   10889:         if ($number==0) {
                   10890:             $result .=
                   10891:                  &Apache::lonhtmlcommon::confirm_success(
                   10892:                      &mt('No IDs found to determine correct answer'),1);
                   10893:             return $result;
                   10894:         }
1.404     www      10895:     }
1.405     www      10896:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10897:         $result .=
                   10898:             &Apache::lonhtmlcommon::confirm_success(
                   10899:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10900:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10901:         return $result;
1.405     www      10902:     }
1.760     raeburn  10903:     my $mimetype;
                   10904:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10905:         my $mm = new File::MMagic;
                   10906:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10907:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10908:             $result.= '<p>'.
                   10909:                 &Apache::lonhtmlcommon::confirm_success(
                   10910:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10911:             return $result;
                   10912:         }
                   10913:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10914:         $result .= '<p>'.
                   10915:             &Apache::lonhtmlcommon::confirm_success(
                   10916:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10917:         return $result;
                   10918:     }
1.410     www      10919: 
                   10920: # Were able to get all the info needed, now analyze the file
                   10921: 
1.411     www      10922:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10923:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10924:     $result.=&Apache::loncommon::start_data_table().
                   10925:              &Apache::loncommon::start_data_table_header_row().
                   10926:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10927:              &Apache::loncommon::end_data_table_header_row().
                   10928:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10929: <td>
1.410     www      10930: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10931: <input type="hidden" name="symb" value="$symb" />
                   10932: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10933: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10934: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10935: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10936: ENDHEADER
1.522     www      10937:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10938:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10939:     } 
1.408     albertel 10940:     my %responses;
                   10941:     my @questiontitles;
1.405     www      10942:     my $errormsg='';
                   10943:     my $number=0;
                   10944:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10945:         if ($mimetype eq 'text/plain') {
                   10946:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10947:         } elsif ($mimetype eq 'text/html') {
                   10948:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10949:         }
                   10950:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10951:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10952:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10953:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10954:     }
1.411     www      10955:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10956:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10957:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10958:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10959:              '<br />';
1.522     www      10960:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10961:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10962:        return $result;
1.522     www      10963:     } 
1.414     www      10964: # Remember Question Titles
                   10965: # FIXME: Possibly need delimiter other than ":"
                   10966:     for (my $i=0;$i<$number;$i++) {
                   10967:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10968:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10969:     }
1.411     www      10970:     my $correct_count=0;
                   10971:     my $student_count=0;
                   10972:     my $unknown_count=0;
1.414     www      10973: # Match answers with usernames
                   10974: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10975:     foreach my $id (keys(%responses)) {
1.410     www      10976:        if ($correct_ids{$id}) {
1.414     www      10977:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10978:           $correct_count++;
1.410     www      10979:        } elsif ($clicker_ids{$id}) {
1.437     www      10980:           if ($clicker_ids{$id}=~/\,/) {
                   10981: # More than one user with the same clicker!
1.632     www      10982:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10983:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10984:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10985:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10986:                            "<select name='multi".$id."'>";
                   10987:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10988:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10989:              }
                   10990:              $result.='</select>';
                   10991:              $unknown_count++;
                   10992:           } else {
                   10993: # Good: found one and only one user with the right clicker
                   10994:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10995:              $student_count++;
                   10996:           }
1.410     www      10997:        } else {
1.632     www      10998:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10999:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11000:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11001:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11002:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11003:                    "\n".&mt("Domain").": ".
                   11004:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11005:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11006:           $unknown_count++;
1.410     www      11007:        }
1.405     www      11008:     }
1.412     www      11009:     $result.='<hr />'.
                   11010:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11011:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11012:        if ($correct_count==0) {
1.696     bisitz   11013:           $errormsg.="Found no correct answers for grading!";
1.412     www      11014:        } elsif ($correct_count>1) {
1.414     www      11015:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11016:        }
                   11017:     }
1.428     www      11018:     if ($number<1) {
                   11019:        $errormsg.="Found no questions.";
                   11020:     }
1.412     www      11021:     if ($errormsg) {
                   11022:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11023:     } else {
                   11024:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11025:     }
1.632     www      11026:     $result.='</form></td>'.
                   11027:              &Apache::loncommon::end_data_table_row().
                   11028:              &Apache::loncommon::end_data_table();
1.614     www      11029:     return $result;
1.400     www      11030: }
                   11031: 
1.405     www      11032: sub iclicker_eval {
1.406     www      11033:     my ($questiontitles,$responses)=@_;
1.405     www      11034:     my $number=0;
                   11035:     my $errormsg='';
                   11036:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11037:         my %components=&Apache::loncommon::record_sep($line);
                   11038:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11039: 	if ($entries[0] eq 'Question') {
                   11040: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11041: 		$$questiontitles[$number]=$entries[$i];
                   11042: 		$number++;
                   11043: 	    }
                   11044: 	}
                   11045: 	if ($entries[0]=~/^\#/) {
                   11046: 	    my $id=$entries[0];
                   11047: 	    my @idresponses;
                   11048: 	    $id=~s/^[\#0]+//;
                   11049: 	    for (my $i=0;$i<$number;$i++) {
                   11050: 		my $idx=3+$i*6;
1.644     www      11051:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11052: 		push(@idresponses,$entries[$idx]);
                   11053: 	    }
                   11054: 	    $$responses{$id}=join(',',@idresponses);
                   11055: 	}
1.405     www      11056:     }
                   11057:     return ($errormsg,$number);
                   11058: }
                   11059: 
1.760     raeburn  11060: sub iclickerxml_eval {
                   11061:     my ($questiontitles,$responses)=@_;
                   11062:     my $number=0;
                   11063:     my $errormsg='';
                   11064:     my @state;
                   11065:     my %respbyid;
                   11066:     my $p = HTML::Parser->new
                   11067:     (
                   11068:         xml_mode => 1,
                   11069:         start_h =>
                   11070:             [sub {
                   11071:                  my ($tagname,$attr) = @_;
                   11072:                  push(@state,$tagname);
                   11073:                  if ("@state" eq "ssn p") {
                   11074:                      my $title = $attr->{qn};
                   11075:                      $title =~ s/(^\s+|\s+$)//g;
                   11076:                      $questiontitles->[$number]=$title;
                   11077:                  } elsif ("@state" eq "ssn p v") {
                   11078:                      my $id = $attr->{id};
                   11079:                      my $entry = $attr->{ans};
                   11080:                      $id=~s/^[\#0]+//;
                   11081:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11082:                      $respbyid{$id}[$number] = $entry;
                   11083:                  }
                   11084:             }, "tagname, attr"],
                   11085:          end_h =>
                   11086:                [sub {
                   11087:                    my ($tagname) = @_;
                   11088:                    if ("@state" eq "ssn p") {
                   11089:                        $number++;
                   11090:                    }
                   11091:                    pop(@state);
                   11092:                 }, "tagname"],
                   11093:     );
                   11094: 
                   11095:     $p->parse($env{'form.upfile'});
                   11096:     $p->eof;
                   11097:     foreach my $id (keys(%respbyid)) {
                   11098:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11099:     }
                   11100:     return ($errormsg,$number);
                   11101: }
                   11102: 
1.419     www      11103: sub interwrite_eval {
                   11104:     my ($questiontitles,$responses)=@_;
                   11105:     my $number=0;
                   11106:     my $errormsg='';
1.420     www      11107:     my $skipline=1;
                   11108:     my $questionnumber=0;
                   11109:     my %idresponses=();
1.419     www      11110:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11111:         my %components=&Apache::loncommon::record_sep($line);
                   11112:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11113:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11114:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11115:         next if $skipline;
                   11116:         if ($entries[0]!=$questionnumber) {
                   11117:            $questionnumber=$entries[0];
                   11118:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11119:            $number++;
1.419     www      11120:         }
1.420     www      11121:         my $id=$entries[4];
                   11122:         $id=~s/^[\#0]+//;
1.421     www      11123:         $id=~s/^v\d*\://i;
                   11124:         $id=~s/[\-\:]//g;
1.420     www      11125:         $idresponses{$id}[$number]=$entries[6];
                   11126:     }
1.524     raeburn  11127:     foreach my $id (keys(%idresponses)) {
1.420     www      11128:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11129:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11130:     }
                   11131:     return ($errormsg,$number);
                   11132: }
                   11133: 
1.666     www      11134: sub turning_eval {
                   11135:     my ($questiontitles,$responses)=@_;
                   11136:     my $number=0;
                   11137:     my $errormsg='';
                   11138:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11139:         my %components=&Apache::loncommon::record_sep($line);
                   11140:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11141:         if ($#entries>$number) { $number=$#entries; }
                   11142:         my $id=$entries[0];
                   11143:         my @idresponses;
                   11144:         $id=~s/^[\#0]+//;
                   11145:         unless ($id) { next; }
                   11146:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11147:             $entries[$idx]=~s/\,/\;/g;
                   11148:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11149:             push(@idresponses,$entries[$idx]);
                   11150:         }
                   11151:         $$responses{$id}=join(',',@idresponses);
                   11152:     }
                   11153:     for (my $i=1; $i<=$number; $i++) {
                   11154:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11155:     }
                   11156:     return ($errormsg,$number);
                   11157: }
                   11158: 
                   11159: 
1.414     www      11160: sub assign_clicker_grades {
1.766     raeburn  11161:     my ($r,$symb) = @_;
1.414     www      11162:     if (!$symb) {return '';}
1.416     www      11163: # See which part we are saving to
1.582     raeburn  11164:     my $res_error;
                   11165:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11166:     if ($res_error) {
                   11167:         return &navmap_errormsg();
                   11168:     }
1.416     www      11169: # FIXME: This should probably look for the first handgradeable part
                   11170:     my $part=$$partlist[0];
                   11171: # Start screen output
1.766     raeburn  11172:     my $result = &Apache::loncommon::start_data_table().
                   11173:                  &Apache::loncommon::start_data_table_header_row().
                   11174:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11175:                  &Apache::loncommon::end_data_table_header_row().
                   11176:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11177: # Get correct result
                   11178: # FIXME: Possibly need delimiter other than ":"
                   11179:     my @correct=();
1.415     www      11180:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11181:     my $number=$env{'form.number'};
                   11182:     if ($gradingmechanism ne 'attendance') {
1.414     www      11183:        foreach my $key (keys(%env)) {
                   11184:           if ($key=~/^form\.correct\:/) {
                   11185:              my @input=split(/\,/,$env{$key});
                   11186:              for (my $i=0;$i<=$#input;$i++) {
                   11187:                  if (($correct[$i]) && ($input[$i]) &&
                   11188:                      ($correct[$i] ne $input[$i])) {
                   11189:                     $result.='<br /><span class="LC_warning">'.
                   11190:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11191:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11192:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11193:                     $correct[$i]=$input[$i];
                   11194:                  }
                   11195:              }
                   11196:           }
                   11197:        }
1.415     www      11198:        for (my $i=0;$i<$number;$i++) {
1.644     www      11199:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11200:              $result.='<br /><span class="LC_error">'.
                   11201:                       &mt('No correct result given for question "[_1]"!',
                   11202:                           $env{'form.question:'.$i}).'</span>';
                   11203:           }
                   11204:        }
1.644     www      11205:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11206:     }
                   11207: # Start grading
1.415     www      11208:     my $pcorrect=$env{'form.pcorrect'};
                   11209:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11210:     my $storecount=0;
1.632     www      11211:     my %users=();
1.415     www      11212:     foreach my $key (keys(%env)) {
1.420     www      11213:        my $user='';
1.415     www      11214:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11215:           $user=$1;
                   11216:        }
                   11217:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11218:           my $id=$1;
                   11219:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11220:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11221:           } elsif ($env{'form.multi'.$id}) {
                   11222:              $user=$env{'form.multi'.$id};
1.420     www      11223:           }
                   11224:        }
1.632     www      11225:        if ($user) {
                   11226:           if ($users{$user}) {
                   11227:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11228:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11229:                       '</span><br />';
                   11230:           }
                   11231:           $users{$user}=1; 
1.415     www      11232:           my @answer=split(/\,/,$env{$key});
                   11233:           my $sum=0;
1.522     www      11234:           my $realnumber=$number;
1.415     www      11235:           for (my $i=0;$i<$number;$i++) {
1.576     www      11236:              if  ($correct[$i] eq '-') {
                   11237:                 $realnumber--;
1.766     raeburn  11238:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11239:                 if ($gradingmechanism eq 'attendance') {
                   11240:                    $sum+=$pcorrect;
1.576     www      11241:                 } elsif ($correct[$i] eq '*') {
1.522     www      11242:                    $sum+=$pcorrect;
1.415     www      11243:                 } else {
1.644     www      11244: # We actually grade if correct or not
                   11245:                    my $increment=$pincorrect;
                   11246: # Special case: numerical answer "0"
                   11247:                    if ($correct[$i] eq '0') {
                   11248:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11249:                          $increment=$pcorrect;
                   11250:                       }
                   11251: # General numerical answer, both evaluate to something non-zero
                   11252:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11253:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11254:                          $increment=$pcorrect;
                   11255:                       }
                   11256: # Must be just alphanumeric
                   11257:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11258:                       $increment=$pcorrect;
1.415     www      11259:                    }
1.644     www      11260:                    $sum+=$increment;
1.415     www      11261:                 }
                   11262:              }
                   11263:           }
1.522     www      11264:           my $ave=$sum/(100*$realnumber);
1.416     www      11265: # Store
                   11266:           my ($username,$domain)=split(/\:/,$user);
                   11267:           my %grades=();
                   11268:           $grades{"resource.$part.solved"}='correct_by_override';
                   11269:           $grades{"resource.$part.awarded"}=$ave;
                   11270:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11271:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11272:                                                  $env{'request.course.id'},
                   11273:                                                  $domain,$username);
                   11274:           if ($returncode ne 'ok') {
                   11275:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11276:           } else {
                   11277:              $storecount++;
                   11278:           }
1.415     www      11279:        }
                   11280:     }
                   11281: # We are done
1.549     hauer    11282:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11283:              '</td>'.
                   11284:              &Apache::loncommon::end_data_table_row().
                   11285:              &Apache::loncommon::end_data_table();
1.614     www      11286:     return $result;
1.414     www      11287: }
                   11288: 
1.582     raeburn  11289: sub navmap_errormsg {
                   11290:     return '<div class="LC_error">'.
                   11291:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11292:            &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  11293:            '</div>';
                   11294: }
1.607     droeschl 11295: 
1.609     www      11296: sub startpage {
1.773     raeburn  11297:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
1.754     raeburn  11298:     my %args;
                   11299:     if ($onload) {
                   11300:          my %loaditems = (
                   11301:                         'onload' => $onload,
                   11302:                       );
                   11303:          $args{'add_entries'} = \%loaditems;
                   11304:     }
1.671     raeburn  11305:     if ($nomenu) {
1.754     raeburn  11306:         $args{'only_body'} = 1; 
1.759     raeburn  11307:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
1.671     raeburn  11308:     } else {
                   11309:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11310:         $args{'bread_crumbs'} = $crumbs;
                   11311:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.765     raeburn  11312:         if ($env{'request.course.id'}) {
                   11313:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11314:         }
1.671     raeburn  11315:     }
1.613     www      11316:     unless ($nodisplayflag) {
1.773     raeburn  11317:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11318:     }
1.607     droeschl 11319: }
1.582     raeburn  11320: 
1.622     www      11321: sub select_problem {
                   11322:     my ($r)=@_;
1.632     www      11323:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11324:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11325:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11326:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11327: }
                   11328: 
1.1       albertel 11329: sub handler {
1.41      ng       11330:     my $request=$_[0];
1.434     albertel 11331:     &reset_caches();
1.646     raeburn  11332:     if ($request->header_only) {
                   11333:         &Apache::loncommon::content_type($request,'text/html');
                   11334:         $request->send_http_header;
                   11335:         return OK;
                   11336:     }
                   11337:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11338: 
1.664     raeburn  11339: # see what command we need to execute
                   11340: 
                   11341:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11342:     my $command=$commands[0];
                   11343: 
1.646     raeburn  11344:     &init_perm();
                   11345:     if (!$env{'request.course.id'}) {
1.664     raeburn  11346:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11347:                 ($command =~ /^scantronupload/)) {
                   11348:             # Not in a course.
                   11349:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11350:             return HTTP_NOT_ACCEPTABLE;
                   11351:         }
1.646     raeburn  11352:     } elsif (!%perm) {
                   11353:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11354:         return OK;
1.41      ng       11355:     }
1.646     raeburn  11356:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11357:     $request->send_http_header;
1.646     raeburn  11358: 
1.160     albertel 11359:     if ($#commands > 0) {
                   11360: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11361:     }
1.608     www      11362: 
                   11363: # see what the symb is
                   11364: 
                   11365:     my $symb=$env{'form.symb'};
                   11366:     unless ($symb) {
                   11367:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11368:        $symb=&Apache::lonnet::symbread($url);
                   11369:     }
1.646     raeburn  11370:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11371: 
1.513     foxr     11372:     $ssi_error = 0;
1.637     www      11373:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11374: #
1.637     www      11375: # Not called from a resource, but inside a course
1.601     www      11376: #    
1.622     www      11377:         &startpage($request,undef,[],1,1);
                   11378:         &select_problem($request);
1.41      ng       11379:     } else {
1.104     albertel 11380: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773     raeburn  11381:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11382:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11383:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11384:                     &choose_task_version_form($symb,$env{'form.student'},
                   11385:                                               $env{'form.userdom'});
                   11386:             }
1.773     raeburn  11387:             my $divforres;
                   11388:             if ($env{'form.student'} eq '') {
                   11389:                 $js .= &part_selector_js();
                   11390:                 $onload = "toggleParts('gradesub');";
                   11391:             } else {
                   11392:                 $divforres = 1;
                   11393:             }
                   11394:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
1.671     raeburn  11395:             if ($versionform) {
                   11396:                 $request->print($versionform);
                   11397:             }
1.773     raeburn  11398: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11399:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11400:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11401:                 &choose_task_version_form($symb,$env{'form.student'},
                   11402:                                           $env{'form.userdom'},
                   11403:                                           $env{'form.inhibitmenu'});
                   11404:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   11405:             if ($versionform) {
                   11406:                 $request->print($versionform);
                   11407:             }
                   11408:             $request->print('<br clear="all" />');
                   11409:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11410: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11411:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11412:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11413: 	    &pickStudentPage($request,$symb);
1.103     albertel 11414: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      11415:             &startpage($request,$symb,
                   11416:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11417:                                        {href=>'',text=>'Select student'},
                   11418:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      11419: 	    &displayPage($request,$symb);
1.104     albertel 11420: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11421:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11422:                                        {href=>'',text=>'Select student'},
                   11423:                                        {href=>'',text=>'Grade student'},
                   11424:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11425: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11426: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      11427:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.773     raeburn  11428:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
1.608     www      11429: 	    &processGroup($request,$symb);
1.104     albertel 11430: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11431:             &startpage($request,$symb);
                   11432: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11433: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11434:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11435: 	    $request->print(&submit_options($request,$symb));
1.598     www      11436:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773     raeburn  11437:             my $js = &part_selector_js();
                   11438:             my $onload = "toggleParts('gradesub');";
                   11439:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11440:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11441:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11442:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11443:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11444:             $request->print(&submit_options_table($request,$symb));
1.598     www      11445:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11446:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11447:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11448: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11449:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11450: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11451: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11452:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11453:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11454: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11455: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11456:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11457:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11458:                                                                              text=>"Modify grades"},
                   11459:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11460: 	    $request->print(&editgrades($request,$symb));
1.602     www      11461:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11462:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11463:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11464: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11465:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11466:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11467: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11468:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11469:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11470:             $request->print(&process_clicker($request,$symb));
1.400     www      11471:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11472:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11473:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11474:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11475:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11476:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11477:                                        {href=>'', text=>'Process clicker file'},
                   11478:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11479:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11480: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11481:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11482: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11483: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11484:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11485: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11486: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11487:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11488: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11489: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11490: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11491:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11492: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11493: 	    } else {
1.257     albertel 11494: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11495: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11496: 		} else {
1.257     albertel 11497: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11498: 		}
1.627     www      11499:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11500: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11501: 	    }
1.246     albertel 11502: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11503:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11504: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11505: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11506:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11507:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11508: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11509:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11510:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11511:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11512: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11513:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11514: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11515: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11516:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11517: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11518:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11519:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11520:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11521:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11522:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11523:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11524:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11525:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11526:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11527:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11528:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11529:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11530:         } elsif ($command eq 'scantronupload_delete' &&
                   11531:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11532:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11533:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11534:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11535:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11536:             $request->print(&checkscantron_results($request,$symb));
                   11537:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773     raeburn  11538:             my $js = &part_selector_js();
                   11539:             my $onload = "toggleParts('gradingMenu');";
                   11540:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11541:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11542:             $request->print(&submit_options_download($request,$symb));
                   11543:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11544:             &startpage($request,$symb,
                   11545:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773     raeburn  11546:     {href=>'', text=>'Download submitted files'}],
                   11547:                undef,undef,undef,undef,undef,undef,undef,1);
1.621     www      11548:             &submit_download_link($request,$symb);
1.106     albertel 11549: 	} elsif ($command) {
1.620     www      11550:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11551: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11552: 	}
1.2       albertel 11553:     }
1.513     foxr     11554:     if ($ssi_error) {
                   11555: 	&ssi_print_error($request);
                   11556:     }
1.671     raeburn  11557:     if ($env{'form.inhibitmenu'}) {
                   11558:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11559:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11560:         &Apache::lonquickgrades::endGradeScreen($request);
                   11561:     }
1.434     albertel 11562:     &reset_caches();
1.646     raeburn  11563:     return OK;
1.44      ng       11564: }
                   11565: 
1.1       albertel 11566: 1;
                   11567: 
1.13      albertel 11568: __END__;
1.531     jms      11569: 
                   11570: 
                   11571: =head1 NAME
                   11572: 
                   11573: Apache::grades
                   11574: 
                   11575: =head1 SYNOPSIS
                   11576: 
                   11577: Handles the viewing of grades.
                   11578: 
                   11579: This is part of the LearningOnline Network with CAPA project
                   11580: described at http://www.lon-capa.org.
                   11581: 
                   11582: =head1 OVERVIEW
                   11583: 
                   11584: Do an ssi with retries:
1.715     bisitz   11585: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11586: 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
                   11587: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11588: 
                   11589: At least the logic that drives this has been pulled out into loncommon.
                   11590: 
                   11591: 
                   11592: 
                   11593: ssi_with_retries - Does the server side include of a resource.
                   11594:                      if the ssi call returns an error we'll retry it up to
                   11595:                      the number of times requested by the caller.
1.715     bisitz   11596:                      If we still have a problem, no text is appended to the
1.531     jms      11597:                      output and we set some global variables.
                   11598:                      to indicate to the caller an SSI error occurred.  
                   11599:                      All of this is supposed to deal with the issues described
1.715     bisitz   11600:                      in LON-CAPA BZ 5631 see:
1.531     jms      11601:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11602:                      by informing the user that this happened.
                   11603: 
                   11604: Parameters:
                   11605:   resource   - The resource to include.  This is passed directly, without
                   11606:                interpretation to lonnet::ssi.
                   11607:   form       - The form hash parameters that guide the interpretation of the resource
                   11608:                
                   11609:   retries    - Number of retries allowed before giving up completely.
                   11610: Returns:
                   11611:   On success, returns the rendered resource identified by the resource parameter.
                   11612: Side Effects:
                   11613:   The following global variables can be set:
                   11614:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11615:                               It is up to the caller to initialize this to false
                   11616:                               if desired.
                   11617:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11618:                               of the resource that could not be rendered by the ssi
                   11619:                               call.
                   11620:    ssi_error_message   - The error string fetched from the ssi response
                   11621:                               in the event of an error.
                   11622: 
                   11623: 
                   11624: =head1 HANDLER SUBROUTINE
                   11625: 
                   11626: ssi_with_retries()
                   11627: 
                   11628: =head1 SUBROUTINES
                   11629: 
                   11630: =over
                   11631: 
1.671     raeburn  11632: =head1 Routines to display previous version of a Task for a specific student
                   11633: 
                   11634: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11635: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11636: requires a proctor to check-in the student, a new version of the Task will
                   11637: be created when the student is checked in to the new opportunity.
                   11638: 
                   11639: If a particular student has tried two or more versions of a particular task,
                   11640: the submission screen provides a user with vgr privileges (e.g., a Course
                   11641: Coordinator) the ability to display a previous version worked on by the
                   11642: student.  By default, the current version is displayed. If a previous version
                   11643: has been selected for display, submission data are only shown that pertain
                   11644: to that particular version, and the interface to submit grades is not shown.
                   11645: 
                   11646: =over 4
                   11647: 
                   11648: =item show_previous_task_version()
                   11649: 
                   11650: Displays a specified version of a student's Task, as the student sees it.
                   11651: 
                   11652: Inputs: 2
                   11653:         request - request object
                   11654:         symb    - unique symb for current instance of resource
                   11655: 
                   11656: Output: None.
                   11657: 
                   11658: Side Effects: calls &show_problem() to print version of Task, with
                   11659:               version contained in form item: $env{'form.previousversion'}
                   11660: 
                   11661: =item choose_task_version_form()
                   11662: 
                   11663: Displays a web form used to select which version of a student's view of a
                   11664: Task should be displayed.  Either launches a pop-up window, or replaces
                   11665: content in existing pop-up, or replaces page in main window.
                   11666: 
                   11667: Inputs: 4
                   11668:         symb    - unique symb for current instance of resource
                   11669:         uname   - username of student
                   11670:         udom    - domain of student
                   11671:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11672:                   breadcrumbs etc., are displayed
                   11673: 
                   11674: Output: 4
                   11675:         current   - student's current version
                   11676:         displayed - student's version being displayed
                   11677:         result    - scalar containing HTML for web form used to switch to
                   11678:                     a different version (or a link to close window, if pop-up).
                   11679:         js        - javascript for processing selection in versions web form
                   11680: 
                   11681: Side Effects: None.
                   11682: 
                   11683: =item previous_display_javascript()
                   11684: 
                   11685: Inputs: 2
                   11686:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11687:                   breadcrumbs etc., are displayed.
                   11688:         current - student's current version number.
                   11689: 
                   11690: Output: 1
                   11691:         js      - javascript for processing selection in versions web form.
                   11692: 
                   11693: Side Effects: None.
                   11694: 
                   11695: =back
                   11696: 
                   11697: =head1 Routines to process bubblesheet data.
                   11698: 
                   11699: =over 4
                   11700: 
1.531     jms      11701: =item scantron_get_correction() : 
                   11702: 
                   11703:    Builds the interface screen to interact with the operator to fix a
                   11704:    specific error condition in a specific scanline
                   11705: 
                   11706:  Arguments:
                   11707:     $r           - Apache request object
                   11708:     $i           - number of the current scanline
                   11709:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11710:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11711:     $line        - full contents of the current scanline
                   11712:     $error       - error condition, valid values are
                   11713:                    'incorrectCODE', 'duplicateCODE',
                   11714:                    'doublebubble', 'missingbubble',
                   11715:                    'duplicateID', 'incorrectID'
                   11716:     $arg         - extra information needed
                   11717:        For errors:
                   11718:          - duplicateID   - paper number that this studentID was seen before on
                   11719:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11720:                            seen on before
                   11721:          - incorrectCODE - current incorrect CODE 
                   11722:          - doublebubble  - array ref of the bubble lines that have double
                   11723:                            bubble errors
                   11724:          - missingbubble - array ref of the bubble lines that have missing
                   11725:                            bubble errors
                   11726: 
1.691     raeburn  11727:    $randomorder - True if exam folder has randomorder set
                   11728:    $randompick  - True if exam folder has randompick set
                   11729:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11730:                      for current line to question number used for same question
                   11731:                      in "Master Seqence" (as seen by Course Coordinator).
                   11732:    $startline   - Reference to hash where key is question number (0 is first)
                   11733:                   and value is number of first bubble line for current student
                   11734:                   or code-based randompick and/or randomorder.
                   11735: 
                   11736: 
                   11737: 
1.531     jms      11738: =item  scantron_get_maxbubble() : 
                   11739: 
1.582     raeburn  11740:    Arguments:
                   11741:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11742:                       failure to retrieve a navmap object.
                   11743:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11744:        calling routine should trap the error condition and display the warning
                   11745:        found in &navmap_errormsg().
                   11746: 
1.649     raeburn  11747:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11748: 
1.531     jms      11749:    Returns the maximum number of bubble lines that are expected to
                   11750:    occur. Does this by walking the selected sequence rendering the
                   11751:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11752:    for what the current value of the problem counter is.
                   11753: 
                   11754:    Caches the results to $env{'form.scantron_maxbubble'},
                   11755:    $env{'form.scantron.bubble_lines.n'}, 
                   11756:    $env{'form.scantron.first_bubble_line.n'} and
                   11757:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11758:    which are the total number of bubble lines, the number of bubble
1.531     jms      11759:    lines for response n and number of the first bubble line for response n,
                   11760:    and a comma separated list of numbers of bubble lines for sub-questions
                   11761:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11762: 
                   11763: 
                   11764: =item  scantron_validate_missingbubbles() : 
                   11765: 
                   11766:    Validates all scanlines in the selected file to not have any
                   11767:     answers that don't have bubbles that have not been verified
                   11768:     to be bubble free.
                   11769: 
                   11770: =item  scantron_process_students() : 
                   11771: 
1.659     raeburn  11772:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11773: 
                   11774:    The parsed scanline hash is added to %env 
                   11775: 
                   11776:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11777:    foreach resource , with the form data of
                   11778: 
                   11779: 	'submitted'     =>'scantron' 
                   11780: 	'grade_target'  =>'grade',
                   11781: 	'grade_username'=> username of student
                   11782: 	'grade_domain'  => domain of student
                   11783: 	'grade_courseid'=> of course
                   11784: 	'grade_symb'    => symb of resource to grade
                   11785: 
                   11786:     This triggers a grading pass. The problem grading code takes care
                   11787:     of converting the bubbled letter information (now in %env) into a
                   11788:     valid submission.
                   11789: 
                   11790: =item  scantron_upload_scantron_data() :
                   11791: 
1.659     raeburn  11792:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11793: 
                   11794: =item  scantron_upload_scantron_data_save() : 
                   11795: 
                   11796:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11797:    has the correct privileges to do so.
                   11798: 
                   11799: = item scantron_upload_delete() :
                   11800: 
                   11801:    Deletes a previously uploaded bubble information data file, if user
                   11802:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11803: 
                   11804: =item  valid_file() :
                   11805: 
                   11806:    Validates that the requested bubble data file exists in the course.
                   11807: 
                   11808: =item  scantron_download_scantron_data() : 
                   11809: 
                   11810:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11811:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11812:    course.
                   11813: 
                   11814: =item  scantron_validate_ID() : 
                   11815: 
                   11816:    Validates all scanlines in the selected file to not have any
1.556     weissno  11817:    invalid or underspecified student/employee IDs
1.531     jms      11818: 
1.582     raeburn  11819: =item navmap_errormsg() :
                   11820: 
                   11821:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11822:    Should be called whenever the request to instantiate a navmap object fails.
                   11823: 
                   11824: =back
1.582     raeburn  11825: 
1.531     jms      11826: =back
                   11827: 
                   11828: =cut

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