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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.596.2.12.2.  0.2.3(ra    4:ar-23): # $Id: grades.pm,v 1.596.2.12.2.60.2.2 2023/03/10 20:23:34 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.596.2.4  raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.596.2.12.2.  1(raebur   46:0): use Apache::lonstathelpers;
1.596.2.4  raeburn    47: use Apache::bridgetask();
1.596.2.12.2.  4(raebur   48:8): use Apache::lontexconvert();
          7(raebur   49:9): use HTML::Parser();
                     50:9): use File::MMagic;
1.170     albertel   51: use String::Similarity;
1.359     www        52: use LONCAPA;
                     53: 
1.315     bowersj2   54: use POSIX qw(floor);
1.87      www        55: 
1.435     foxr       56: 
1.513     foxr       57: 
1.435     foxr       58: my %perm=();
1.596.2.12.2.  (raeburn   59:): my %old_essays=();
1.447     foxr       60: 
1.513     foxr       61: #  These variables are used to recover from ssi errors
                     62: 
                     63: my $ssi_retries = 5;
                     64: my $ssi_error;
                     65: my $ssi_error_resource;
                     66: my $ssi_error_message;
                     67: 
                     68: 
                     69: sub ssi_with_retries {
                     70:     my ($resource, $retries, %form) = @_;
                     71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     72:     if ($response->is_error) {
                     73: 	$ssi_error          = 1;
                     74: 	$ssi_error_resource = $resource;
                     75: 	$ssi_error_message  = $response->code . " " . $response->message;
                     76:     }
                     77: 
                     78:     return $content;
                     79: 
                     80: }
                     81: #
                     82: #  Prodcuces an ssi retry failure error message to the user:
                     83: #
                     84: 
                     85: sub ssi_print_error {
                     86:     my ($r) = @_;
1.516     raeburn    87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     88:     $r->print('
                     89: <br />
                     90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     91: <p>
                     92: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     94: '.&mt('Error:').' '.$ssi_error_message.'
                     95: </p>
                     96: <p>'.
                     97: &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 />'.
                     98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     99: '</p>');
                    100:     return;
1.513     foxr      101: }
                    102: 
1.44      ng        103: #
1.146     albertel  104: # --- Retrieve the parts from the metadata file.---
1.596.2.12.2.  1(raebur  105:0): # Returns an array of everything that the resources stores away
                    106:0): #
                    107:0): 
1.44      ng        108: sub getpartlist {
1.582     raeburn   109:     my ($symb,$errorref) = @_;
1.439     albertel  110: 
                    111:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   112:     unless (ref($navmap)) {
                    113:         if (ref($errorref)) { 
                    114:             $$errorref = 'navmap';
                    115:             return;
                    116:         }
                    117:     }
1.439     albertel  118:     my $res      = $navmap->getBySymb($symb);
                    119:     my $partlist = $res->parts();
                    120:     my $url      = $res->src();
                    121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    122: 
1.146     albertel  123:     my @stores;
1.439     albertel  124:     foreach my $part (@{ $partlist }) {
1.146     albertel  125: 	foreach my $key (@metakeys) {
                    126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    127: 	}
                    128:     }
                    129:     return @stores;
1.2       albertel  130: }
                    131: 
1.129     ng        132: #--- Format fullname, username:domain if different for display
                    133: #--- Use anywhere where the student names are listed
                    134: sub nameUserString {
                    135:     my ($type,$fullname,$uname,$udom) = @_;
                    136:     if ($type eq 'header') {
1.485     albertel  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        138:     } else {
1.398     albertel  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        141:     }
                    142: }
                    143: 
1.44      ng        144: #--- Get the partlist and the response type for a given problem. ---
                    145: #--- Indicate if a response type is coded handgraded or not. ---
1.596.2.12.2.  1(raebur  146:0): #--- Count responseIDs, essayresponse items, and dropbox items ---
                    147:0): #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        148: sub response_type {
1.582     raeburn   149:     my ($symb,$response_error) = @_;
1.377     albertel  150: 
                    151:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   152:     unless (ref($navmap)) {
                    153:         if (ref($response_error)) {
                    154:             $$response_error = 1;
                    155:         }
                    156:         return;
                    157:     }
1.377     albertel  158:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   159:     unless (ref($res)) {
                    160:         $$response_error = 1;
                    161:         return;
                    162:     }
1.377     albertel  163:     my $partlist = $res->parts();
1.596.2.12.2.  1(raebur  164:0):     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  165:     my %vPart = 
                    166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  167:     my (%response_types,%handgrade);
                    168:     foreach my $part (@{ $partlist }) {
1.392     albertel  169: 	next if (%vPart && !exists($vPart{$part}));
                    170: 
1.377     albertel  171: 	my @types = $res->responseType($part);
                    172: 	my @ids = $res->responseIds($part);
                    173: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.596.2.12.2.  1(raebur  174:0):             $numresp ++;
1.377     albertel  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.596.2.12.2.  1(raebur  176:0):             if ($types[$i] eq 'essay') {
                    177:0):                 $numessay ++;
                    178:0):                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    179:0):                     $numdropbox ++;
                    180:0):                 }
                    181:0):             }
1.377     albertel  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    184: 				     '.handgrade',$symb);
1.41      ng        185: 	}
                    186:     }
1.596.2.12.2.  1(raebur  187:0):     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        188: }
                    189: 
1.375     albertel  190: sub flatten_responseType {
                    191:     my ($responseType) = @_;
                    192:     my @part_response_id =
                    193: 	map { 
                    194: 	    my $part = $_;
                    195: 	    map {
                    196: 		[$part,$_]
                    197: 		} sort(keys(%{ $responseType->{$part} }));
                    198: 	} sort(keys(%$responseType));
                    199:     return @part_response_id;
                    200: }
                    201: 
1.207     albertel  202: sub get_display_part {
1.324     albertel  203:     my ($partID,$symb)=@_;
1.207     albertel  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    205:     if (defined($display) and $display ne '') {
1.577     bisitz    206:         $display.= ' (<span class="LC_internal_info">'
                    207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  208:     } else {
                    209: 	$display=$partID;
                    210:     }
                    211:     return $display;
                    212: }
1.269     raeburn   213: 
1.596.2.12.2.  1(raebur  214:0): #--- Show parts and response type
1.118     ng        215: sub showResourceInfo {
1.596.2.12.2.  1(raebur  216:0):     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    217:0):     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    218:0):         return '<br clear="all">';
                    219:0):     }
                    220:0):     my $coltitle = &mt('Problem Part Shown');
                    221:0):     if ($checkboxes) {
                    222:0):         $coltitle = &mt('Problem Part');
                    223:0):     } else {
                    224:0):         my $checkedparts = 0;
                    225:0):         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    226:0):             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    227:0):                 $checkedparts ++;
                    228:0):             }
                    229:0):         }
                    230:0):         if ($checkedparts == scalar(@{$partlist})) {
                    231:0):             return '<br clear="all">';
                    232:0):         }
                    233:0):         if ($uploads) {
                    234:0):             $coltitle = &mt('Problem Part Selected');
1.582     raeburn   235:         }
                    236:     }
1.596.2.12.2.  1(raebur  237:0):     my $result = '<div class="LC_left_float" style="display:inline-block;">';
1.584     bisitz    238:     if ($checkboxes) {
1.596.2.12.2.  1(raebur  239:0):         my $legend = &mt('Parts to display');
                    240:0):         if ($uploads) {
                    241:0):             $legend = &mt('Part(s) with dropbox');
                    242:0):         }
                    243:0):         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    244:0):                    '<span class="LC_nobreak">'.
                    245:0):                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    246:0):                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    247:0):                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    248:0):                    &mt('Selected parts').'</label></span>'.
                    249:0):                    '<div id="LC_partselector" style="display:none">';
1.584     bisitz    250:     }
1.596.2.12.2.  1(raebur  251:0):     $result .= &Apache::loncommon::start_data_table()
                    252:0):               .&Apache::loncommon::start_data_table_header_row();
                    253:0):     if ($checkboxes) {
                    254:0):         $result .= '<th>'.&mt('Display?').'</th>';
                    255:0):     }
                    256:0):     $result .= '<th>'.$coltitle.'</th>'
                    257:0):               .'<th>'.&mt('Res. ID').'</th>'
                    258:0):               .'<th>'.&mt('Type').'</th>'
                    259:0):               .&Apache::loncommon::end_data_table_header_row();
1.154     albertel  260:     my %partsseen;
1.524     raeburn   261:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    263:             my $responsetype = $responseType->{$partID}->{$resID};
1.596.2.12.2.  1(raebur  264:0):             if ($uploads) {
                    265:0):                 next unless ($responsetype eq 'essay');
                    266:0):                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    267:0):             }
                    268:0):             my $display_part=&get_display_part($partID,$symb);
                    269:0):             if (exists($partsseen{$partID})) {
                    270:0):                 $result.=&Apache::loncommon::continue_data_table_row();
                    271:0):             } else {
                    272:0):                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    273:0):                 $result.=&Apache::loncommon::start_data_table_row().
                    274:0):                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    275:0):                 if ($checkboxes) {
                    276:0):                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    277:0):                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
1.584     bisitz    278:                 } else {
1.596.2.12.2.  1(raebur  279:0):                     $result.=$display_part.'</td>';
1.584     bisitz    280:                 }
                    281:             }
1.596.2.12.2.  1(raebur  282:0):             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
1.584     bisitz    283:                     .'<td>'.&mt($responsetype).'</td>'
                    284:                     .&Apache::loncommon::end_data_table_row();
                    285:         }
1.118     ng        286:     }
1.584     bisitz    287:     $result.=&Apache::loncommon::end_data_table();
1.596.2.12.2.  1(raebur  288:0):     if ($checkboxes) {
                    289:0):         $result .= '</div></fieldset>';
                    290:0):     }
                    291:0):     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
          2(raebur  292:0):     if (!keys(%partsseen)) {
                    293:0):         $result = '';
                    294:0):         if ($uploads) {
                    295:0):             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    296:0):                    '<p class="LC_info">'.
                    297:0):                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    298:0):                    '</p>';
                    299:0):         } else {
                    300:0):             return '<br clear="all" />';
                    301:0):         }
                    302:0):     }  
          1(raebur  303:0):     return $result;
                    304:0): }
                    305:0): 
                    306:0): sub part_selector_js {
                    307:0):     my $js = <<"END";
                    308:0): function toggleParts(formname) {
                    309:0):     if (document.getElementById('LC_partselector')) {
                    310:0):         var index = '';
                    311:0):         if (document.forms.length) {
                    312:0):             for (var i=0; i<document.forms.length; i++) {
                    313:0):                 if (document.forms[i].name == formname) {
                    314:0):                     index = i;
                    315:0):                     break;
                    316:0):                 }
                    317:0):             }
                    318:0):         }
                    319:0):         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    320:0):             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    321:0):                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    322:0):                    var val = document.forms[index].elements['chooseparts'][i].value;
                    323:0):                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    324:0):                         document.getElementById('LC_partselector').style.display = 'block';
                    325:0):                     } else {
                    326:0):                         document.getElementById('LC_partselector').style.display = 'none';
                    327:0):                     }
                    328:0):                 }
                    329:0):             }
                    330:0):         }
                    331:0):     }
                    332:0): }
                    333:0): END
                    334:0):     return &Apache::lonhtmlcommon::scripttag($js);
1.118     ng        335: }
                    336: 
1.434     albertel  337: sub reset_caches {
                    338:     &reset_analyze_cache();
                    339:     &reset_perm();
1.596.2.12.2.  (raeburn  340:):     &reset_old_essays();
1.434     albertel  341: }
                    342: 
                    343: {
                    344:     my %analyze_cache;
1.557     raeburn   345:     my %analyze_cache_formkeys;
1.148     albertel  346: 
1.434     albertel  347:     sub reset_analyze_cache {
                    348: 	undef(%analyze_cache);
1.557     raeburn   349:         undef(%analyze_cache_formkeys);
1.434     albertel  350:     }
                    351: 
                    352:     sub get_analyze {
1.596.2.12.2.  (raeburn  353:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  354: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   355:         if ($type eq 'randomizetry') {
                    356:             if ($trial ne '') {
                    357:                 $key .= "\0".$trial;
                    358:             }
                    359:         }
1.557     raeburn   360: 	if (exists($analyze_cache{$key})) {
                    361:             my $getupdate = 0;
                    362:             if (ref($add_to_hash) eq 'HASH') {
                    363:                 foreach my $item (keys(%{$add_to_hash})) {
                    364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    366:                             $getupdate = 1;
                    367:                             last;
                    368:                         }
                    369:                     } else {
                    370:                         $getupdate = 1;
                    371:                     }
                    372:                 }
                    373:             }
                    374:             if (!$getupdate) {
                    375:                 return $analyze_cache{$key};
                    376:             }
                    377:         }
1.434     albertel  378: 
                    379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    380: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   381:         my %form = ('grade_target'      => 'analyze',
                    382:                     'grade_domain'      => $udom,
                    383:                     'grade_symb'        => $symb,
                    384:                     'grade_courseid'    =>  $env{'request.course.id'},
                    385:                     'grade_username'    => $uname,
                    386:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  387:):         if ($bubbles_per_row ne '') {
                    388:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    389:):         }
1.596.2.2  raeburn   390:         if ($type eq 'randomizetry') {
                    391:             $form{'grade_questiontype'} = $type;
                    392:             if ($rndseed ne '') {
                    393:                 $form{'grade_rndseed'} = $rndseed;
                    394:             }
                    395:         }
1.557     raeburn   396:         if (ref($add_to_hash)) {
                    397:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   398:         }
1.557     raeburn   399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   402:         if (ref($add_to_hash) eq 'HASH') {
                    403:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    404:         } else {
                    405:             $analyze_cache_formkeys{$key} = {};
                    406:         }
1.434     albertel  407: 	return $analyze_cache{$key} = \%analyze;
                    408:     }
                    409: 
                    410:     sub get_order {
1.596.2.2  raeburn   411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  413: 	return $analyze->{"$partid.$respid.shown"};
                    414:     }
                    415: 
                    416:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   420:         if (ref($foils) eq 'ARRAY') {
                    421: 	    foreach my $foil (@{$foils}) {
                    422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    423: 		    return $foil;
                    424: 	        }
1.434     albertel  425: 	    }
                    426: 	}
                    427:     }
1.554     raeburn   428: 
                    429:     sub scantron_partids_tograde {
1.596.2.12.2.  1(raebur  430:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   431:         my (%analysis,@parts);
                    432:         if (ref($resource)) {
                    433:             my $symb = $resource->symb();
1.557     raeburn   434:             my $add_to_form;
                    435:             if ($check_for_randomlist) {
                    436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    437:             }
1.596.2.12.2.  1(raebur  438:7):             if ($scancode) {
                    439:7):                 if (ref($add_to_form) eq 'HASH') {
                    440:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    441:7):                 } else {
                    442:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    443:7):                 }
                    444:7):             }
          (raeburn  445:):             my $analyze =
                    446:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    447:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   448:             if (ref($analyze) eq 'HASH') {
                    449:                 %analysis = %{$analyze};
                    450:             }
                    451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    452:                 foreach my $part (@{$analysis{'parts'}}) {
                    453:                     my ($id,$respid) = split(/\./,$part);
                    454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    455:                         push(@parts,$part);
                    456:                     }
                    457:                 }
                    458:             }
                    459:         }
                    460:         return (\%analysis,\@parts);
                    461:     }
                    462: 
1.148     albertel  463: }
1.434     albertel  464: 
1.118     ng        465: #--- Clean response type for display
1.335     albertel  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    467: #        response types only.
1.118     ng        468: sub cleanRecord {
1.336     albertel  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  471:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  472:     if ($response =~ /^(option|rank)$/) {
                    473: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  474:4):         my @answer = %answer;
                    475:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    477: 	my ($toprow,$bottomrow);
                    478: 	foreach my $foil (@$order) {
                    479: 	    if ($grading{$foil} == 1) {
                    480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    481: 	    } else {
                    482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    483: 	    }
1.398     albertel  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  485: 	}
                    486: 	return '<blockquote><table border="1">'.
1.466     albertel  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   489: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  490:     } elsif ($response eq 'match') {
                    491: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  492:4):         my @answer = %answer;
                    493:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    496: 	my ($toprow,$middlerow,$bottomrow);
                    497: 	foreach my $foil (@$order) {
                    498: 	    my $item=shift(@items);
                    499: 	    if ($grading{$foil} == 1) {
                    500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  502: 	    } else {
                    503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  505: 	    }
1.398     albertel  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        507: 	}
1.126     ng        508: 	return '<blockquote><table border="1">'.
1.466     albertel  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  511: 	    $middlerow.'</tr>'.
1.466     albertel  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   513: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  514:     } elsif ($response eq 'radiobutton') {
                    515: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  1(raebur  516:0):         my @answer = %answer;
                    517:0):         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  518: 	my ($toprow,$bottomrow);
1.434     albertel  519: 	my $correct = 
1.596.2.2  raeburn   520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  521: 	foreach my $foil (@$order) {
1.148     albertel  522: 	    if (exists($answer{$foil})) {
1.434     albertel  523: 		if ($foil eq $correct) {
1.466     albertel  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  525: 		} else {
1.466     albertel  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  527: 		}
                    528: 	    } else {
1.466     albertel  529: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  530: 	    }
1.398     albertel  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  532: 	}
                    533: 	return '<blockquote><table border="1">'.
1.466     albertel  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   536: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  537:     } elsif ($response eq 'essay') {
1.257     albertel  538: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        542: 
1.257     albertel  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    548: 	    $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        549: 	}
1.596.2.12.2.  4(raebur  550:8):         $answer = &Apache::lontexconvert::msgtexconverted($answer);
          2(raebur  551:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  552:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  553:4):         my $result=&mt('Smile representation: [_1]',
                    554:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    557: 	return $result;
1.335     albertel  558:     } elsif ( $response eq 'Task') {
                    559: 	if ( $answer eq 'SUBMITTED') {
                    560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  562: 	    return $result;
                    563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    565: 			       keys(%{$record}));
                    566: 	    return join('<br />',($version,@matches));
                    567: 			       
                    568: 			       
                    569: 	} else {
                    570: 	    my $result =
                    571: 		'<p>'
                    572: 		.&mt('Overall result: [_1]',
                    573: 		     $record->{$version."resource.$respid.$partid.status"})
                    574: 		.'</p>';
                    575: 	    
                    576: 	    $result .= '<ul>';
                    577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    578: 			     keys(%{$record}));
                    579: 	    foreach my $grade (sort(@grade)) {
                    580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    582: 				     $dim, $record->{$grade}).
                    583: 			  '</li>';
                    584: 	    }
                    585: 	    $result.='</ul>';
                    586: 	    return $result;
                    587: 	}
1.596.2.12.2.  8(raebur  588:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    589:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  590: 	$answer = 
                    591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    592: 							      $answer);
1.596.2.12.2.  1(raebur  593:0): 	return $answer;
1.122     ng        594:     }
1.596.2.12.2.  8(raebur  595:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        596: }
                    597: 
                    598: #-- A couple of common js functions
                    599: sub commonJSfunctions {
                    600:     my $request = shift;
1.596.2.12.2.  1(raebur  601:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        602:     function radioSelection(radioButton) {
                    603: 	var selection=null;
                    604: 	if (radioButton.length > 1) {
                    605: 	    for (var i=0; i<radioButton.length; i++) {
                    606: 		if (radioButton[i].checked) {
                    607: 		    return radioButton[i].value;
                    608: 		}
                    609: 	    }
                    610: 	} else {
                    611: 	    if (radioButton.checked) return radioButton.value;
                    612: 	}
                    613: 	return selection;
                    614:     }
                    615: 
                    616:     function pullDownSelection(selectOne) {
                    617: 	var selection="";
                    618: 	if (selectOne.length > 1) {
                    619: 	    for (var i=0; i<selectOne.length; i++) {
                    620: 		if (selectOne[i].selected) {
                    621: 		    return selectOne[i].value;
                    622: 		}
                    623: 	    }
                    624: 	} else {
1.138     albertel  625:             // only one value it must be the selected one
                    626: 	    return selectOne.value;
1.118     ng        627: 	}
                    628:     }
                    629: COMMONJSFUNCTIONS
                    630: }
                    631: 
1.44      ng        632: #--- Dumps the class list with usernames,list of sections,
                    633: #--- section, ids and fullnames for each user.
                    634: sub getclasslist {
1.596.2.12.2.  1(raebur  635:0):     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  636:     my @getsec;
1.450     banghart  637:     my @getgroup;
1.442     banghart  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  639:     if (!ref($getsec)) {
                    640: 	if ($getsec ne '' && $getsec ne 'all') {
                    641: 	    @getsec=($getsec);
                    642: 	}
                    643:     } else {
                    644: 	@getsec=@{$getsec};
                    645:     }
                    646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  647:     if (!ref($getgroup)) {
                    648: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    649: 	    @getgroup=($getgroup);
                    650: 	}
                    651:     } else {
                    652: 	@getgroup=@{$getgroup};
                    653:     }
                    654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  655: 
1.449     banghart  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  657:     # Bail out if we were unable to get the classlist
1.56      matthew   658:     return if (! defined($classlist));
1.449     banghart  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   660:     #
                    661:     my %sections;
                    662:     my %fullnames;
1.596.2.12.2.  1(raebur  663:0):     my ($cdom,$cnum,$partlist);
                    664:0):     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    665:0):         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    666:0):         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    667:0):         my $res_error;
                    668:0):         ($partlist) = &response_type($symb,\$res_error);
                    669:0):     }
1.205     matthew   670:     foreach my $student (keys(%$classlist)) {
                    671:         my $end      = 
                    672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    673:         my $start    = 
                    674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    675:         my $id       = 
                    676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    677:         my $section  = 
                    678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    679:         my $fullname = 
                    680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    681:         my $status   = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  683:         my $group   = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        685: 	# filter students according to status selected
1.596.2.12.2.  1(raebur  686:0): 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  687: 	    if (!($stu_status =~ $status)) {
1.450     banghart  688: 		delete($classlist->{$student});
1.76      ng        689: 		next;
                    690: 	    }
                    691: 	}
1.450     banghart  692: 	# filter students according to groups selected
1.453     banghart  693: 	my @stu_groups = split(/,/,$group);
1.450     banghart  694: 	if (@getgroup) {
                    695: 	    my $exclude = 1;
1.454     banghart  696: 	    foreach my $grp (@getgroup) {
                    697: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  698: 	            if ($stu_group eq $grp) {
                    699: 	                $exclude = 0;
                    700:     	            } 
1.450     banghart  701: 	        }
1.453     banghart  702:     	        if (($grp eq 'none') && !$group) {
1.596.2.12.2.  1(raebur  703:0):         	    $exclude = 0;
1.453     banghart  704:         	}
1.450     banghart  705: 	    }
                    706: 	    if ($exclude) {
                    707: 	        delete($classlist->{$student});
1.596.2.12.2.  1(raebur  708:0): 		next;
1.450     banghart  709: 	    }
                    710: 	}
1.596.2.12.2.  1(raebur  711:0):         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    712:0):             my $udom =
                    713:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    714:0):             my $uname =
                    715:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    716:0):             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    717:0):                 if ($submitonly eq 'queued') {
                    718:0):                     my %queue_status =
                    719:0):                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    720:0):                                                                 $udom,$uname);
                    721:0):                     if (!defined($queue_status{'gradingqueue'})) {
                    722:0):                         delete($classlist->{$student});
                    723:0):                         next;
                    724:0):                     }
                    725:0):                 } else {
                    726:0):                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    727:0):                     my $submitted = 0;
                    728:0):                     my $graded = 0;
                    729:0):                     my $incorrect = 0;
                    730:0):                     foreach (keys(%status)) {
                    731:0):                         $submitted = 1 if ($status{$_} ne 'nothing');
                    732:0):                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    733:0):                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    734:0): 
                    735:0):                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    736:0):                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    737:0):                             $submitted = 0;
                    738:0):                         }
                    739:0):                     }
                    740:0):                     if (!$submitted && ($submitonly eq 'yes' ||
                    741:0):                                         $submitonly eq 'incorrect' ||
                    742:0):                                         $submitonly eq 'graded')) {
                    743:0):                         delete($classlist->{$student});
                    744:0):                         next;
                    745:0):                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    746:0):                         delete($classlist->{$student});
                    747:0):                         next;
                    748:0):                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    749:0):                         delete($classlist->{$student});
                    750:0):                         next;
                    751:0):                     }
                    752:0):                 }
                    753:0):             }
                    754:0):         }
1.205     matthew   755: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  756: 	if (&canview($section)) {
1.291     albertel  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  758: 		$sections{$section}++;
1.450     banghart  759: 		if ($classlist->{$student}) {
                    760: 		    $fullnames{$student}=$fullname;
                    761: 		}
1.103     albertel  762: 	    } else {
1.205     matthew   763: 		delete($classlist->{$student});
1.103     albertel  764: 	    }
                    765: 	} else {
1.205     matthew   766: 	    delete($classlist->{$student});
1.103     albertel  767: 	}
1.44      ng        768:     }
1.56      matthew   769:     my @sections = sort(keys(%sections));
                    770:     return ($classlist,\@sections,\%fullnames);
1.44      ng        771: }
                    772: 
1.103     albertel  773: sub canmodify {
                    774:     my ($sec)=@_;
                    775:     if ($perm{'mgr'}) {
                    776: 	if (!defined($perm{'mgr_section'})) {
                    777: 	    # can modify whole class
                    778: 	    return 1;
                    779: 	} else {
                    780: 	    if ($sec eq $perm{'mgr_section'}) {
                    781: 		#can modify the requested section
                    782: 		return 1;
                    783: 	    } else {
1.596.2.12.2.  1(raebur  784:0): 		# can't modify the requested section
1.103     albertel  785: 		return 0;
                    786: 	    }
                    787: 	}
                    788:     }
                    789:     #can't modify
                    790:     return 0;
                    791: }
                    792: 
                    793: sub canview {
                    794:     my ($sec)=@_;
                    795:     if ($perm{'vgr'}) {
                    796: 	if (!defined($perm{'vgr_section'})) {
1.596.2.12.2.  1(raebur  797:0): 	    # can view whole class
1.103     albertel  798: 	    return 1;
                    799: 	} else {
                    800: 	    if ($sec eq $perm{'vgr_section'}) {
1.596.2.12.2.  1(raebur  801:0): 		#can view the requested section
1.103     albertel  802: 		return 1;
                    803: 	    } else {
1.596.2.12.2.  1(raebur  804:0): 		# can't view the requested section
1.103     albertel  805: 		return 0;
                    806: 	    }
                    807: 	}
                    808:     }
1.596.2.12.2.  1(raebur  809:0):     #can't view
1.103     albertel  810:     return 0;
                    811: }
                    812: 
1.44      ng        813: #--- Retrieve the grade status of a student for all the parts
                    814: sub student_gradeStatus {
1.324     albertel  815:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        817:     my %partstatus = ();
                    818:     foreach (@$partlist) {
1.128     ng        819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        820: 	$status              = 'nothing' if ($status eq '');
                    821: 	$partstatus{$_}      = $status;
                    822: 	my $subkey           = "resource.$_.submitted_by";
                    823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    824:     }
                    825:     return %partstatus;
                    826: }
                    827: 
1.45      ng        828: # hidden form and javascript that calls the form
                    829: # Use by verifyscript and viewgrades
                    830: # Shows a student's view of problem and submission
                    831: sub jscriptNform {
1.324     albertel  832:     my ($symb) = @_;
1.442     banghart  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  1(raebur  834:0):     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        835: 	'    function viewOneStudent(user,domain) {'."\n".
                    836: 	'	document.onestudent.student.value = user;'."\n".
                    837: 	'	document.onestudent.userdom.value = domain;'."\n".
                    838: 	'	document.onestudent.submit();'."\n".
                    839: 	'    }'."\n".
1.596.2.12.2.  1(raebur  840:0): 	"\n");
1.45      ng        841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        844: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    845: 	'<input type="hidden" name="student" value="" />'."\n".
                    846: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    847: 	'</form>'."\n";
                    848:     return $jscript;
                    849: }
1.39      ng        850: 
1.447     foxr      851: 
                    852: 
1.315     bowersj2  853: # Given the score (as a number [0-1] and the weight) what is the final
                    854: # point value? This function will round to the nearest tenth, third,
                    855: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  856: sub compute_points {
1.315     bowersj2  857:     my ($score, $weight) = @_;
                    858:     
                    859:     my $tolerance = .00001;
                    860:     my $points = $score * $weight;
                    861: 
                    862:     # Check for nearness to 1/x.
                    863:     my $check_for_nearness = sub {
                    864:         my ($factor) = @_;
                    865:         my $num = ($points * $factor) + $tolerance;
                    866:         my $floored_num = floor($num);
1.316     albertel  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  868:             return $floored_num / $factor;
                    869:         }
                    870:         return $points;
                    871:     };
                    872: 
                    873:     $points = $check_for_nearness->(10);
                    874:     $points = $check_for_nearness->(3);
                    875:     $points = $check_for_nearness->(4);
                    876:     
                    877:     return $points;
                    878: }
                    879: 
1.44      ng        880: #------------------ End of general use routines --------------------
1.87      www       881: 
                    882: #
                    883: # Find most similar essay
                    884: #
                    885: 
                    886: sub most_similar {
1.596.2.12.2.  (raeburn  887:):     my ($uname,$udom,$symb,$uessay)=@_;
                    888:): 
                    889:):     unless ($symb) { return ''; }
                    890:): 
                    891:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       892: 
                    893: # ignore spaces and punctuation
                    894: 
                    895:     $uessay=~s/\W+/ /gs;
                    896: 
1.282     www       897: # ignore empty submissions (occuring when only files are sent)
                    898: 
1.596.2.4  raeburn   899:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       900: 
1.87      www       901: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       902:     my $limit=0.6;
1.87      www       903:     my $sname='';
                    904:     my $sdom='';
                    905:     my $scrsid='';
                    906:     my $sessay='';
                    907: # go through all essays ...
1.596.2.12.2.  (raeburn  908:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       910: # ... except the same student
1.426     albertel  911:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  912:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  913: 	$tessay=~s/\W+/ /gs;
1.87      www       914: # String similarity gives up if not even limit
1.426     albertel  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       916: # Found one
1.426     albertel  917: 	if ($tsimilar>$limit) {
                    918: 	    $limit=$tsimilar;
                    919: 	    $sname=$tname;
                    920: 	    $sdom=$tdom;
                    921: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  922:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  923: 	}
1.87      www       924:     }
1.88      www       925:     if ($limit>0.6) {
1.87      www       926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    927:     } else {
                    928:        return ('','','','',0);
                    929:     }
                    930: }
                    931: 
1.44      ng        932: #-------------------------------------------------------------------
                    933: 
                    934: #------------------------------------ Receipt Verification Routines
1.45      ng        935: #
1.596.2.12.2.  1(raebur  936:0): 
                    937:0): sub initialverifyreceipt {
                    938:0):    my ($request,$symb) = @_;
                    939:0):    &commonJSfunctions($request);
                    940:0):    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
                    941:0):         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    942:0):         '-<input type="text" name="receipt" size="4" />'.
                    943:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    944:0):         '<input type="hidden" name="command" value="verify" />'.
                    945:0):         "</form>\n";
                    946:0): }
                    947:0): 
1.44      ng        948: #--- Check whether a receipt number is valid.---
                    949: sub verifyreceipt {
1.596.2.12.2.  1(raebur  950:0):     my ($request,$symb) = @_;
1.44      ng        951: 
1.257     albertel  952:     my $courseid = $env{'request.course.id'};
1.184     www       953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  954: 	$env{'form.receipt'};
1.44      ng        955:     $receipt     =~ s/[^\-\d]//g;
                    956: 
1.596.2.12.2.  1(raebur  957:0):     my $title =
1.487     albertel  958: 	'<h3><span class="LC_info">'.
1.596.2.12.2.  1(raebur  959:0): 	&mt('Verifying Receipt Number [_1]',$receipt).
                    960:0): 	'</span></h3>'."\n";
1.44      ng        961: 
                    962:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   963:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  964:     
                    965:     my $receiptparts=0;
1.390     albertel  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  968:     my $parts=['0'];
1.582     raeburn   969:     if ($receiptparts) {
                    970:         my $res_error; 
                    971:         ($parts)=&response_type($symb,\$res_error);
                    972:         if ($res_error) {
                    973:             return &navmap_errormsg();
                    974:         } 
                    975:     }
1.486     albertel  976:     
                    977:     my $header = 
                    978: 	&Apache::loncommon::start_data_table().
                    979: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  983:     if ($receiptparts) {
1.487     albertel  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  985:     }
                    986:     $header.=
                    987: 	&Apache::loncommon::end_data_table_header_row();
                    988: 
1.294     albertel  989:     foreach (sort 
                    990: 	     {
                    991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    993: 		 }
                    994: 		 return $a cmp $b;
                    995: 	     } (keys(%$fullname))) {
1.44      ng        996: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  997: 	foreach my $part (@$parts) {
                    998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  999: 		$contents.=
                   1000: 		    &Apache::loncommon::start_data_table_row().
                   1001: 		    '<td>&nbsp;'."\n".
1.177     albertel 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1006: 		if ($receiptparts) {
                   1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1008: 		}
1.486     albertel 1009: 		$contents.= 
                   1010: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1011: 		
                   1012: 		$matches++;
                   1013: 	    }
1.44      ng       1014: 	}
                   1015:     }
                   1016:     if ($matches == 0) {
1.584     bisitz   1017:         $string = $title
                   1018:                  .'<p class="LC_warning">'
                   1019:                  .&mt('No match found for the above receipt number.')
                   1020:                  .'</p>';
1.44      ng       1021:     } else {
1.324     albertel 1022: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1023: 	    '<p>'.
1.584     bisitz   1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1025: 	    '</p>'.
1.486     albertel 1026: 	    $header.
                   1027: 	    $contents.
                   1028: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1029:     }
1.596.2.12.2.  1(raebur 1030:0):     return $string;
1.44      ng       1031: }
                   1032: 
                   1033: #--- This is called by a number of programs.
                   1034: #--- Called from the Grading Menu - View/Grade an individual student
                   1035: #--- Also called directly when one clicks on the subm button 
                   1036: #    on the problem page.
1.30      ng       1037: sub listStudents {
1.596.2.12.2.  1(raebur 1038:0):     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1039: 
1.257     albertel 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.596.2.12.2.  1(raebur 1044:0):     unless ($submitonly) {
                   1045:0):         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   1046:0):     }
                   1047:0): 
                   1048:0):     my $result='';
                   1049:0):     my $res_error;
                   1050:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
1.118     ng       1051: 
1.596.2.12.2.  1(raebur 1052:0):     my $table;
                   1053:0):     if (ref($partlist) eq 'ARRAY') {
                   1054:0):         if (scalar(@$partlist) > 1 ) {
                   1055:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1056:0):         } elsif ($divforres) {
                   1057:0):             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1058:0):         } else {
                   1059:0):             $table = '<br clear="all" />';
                   1060:0):         }
                   1061:0):     }
1.49      albertel 1062: 
1.596.2.12.2.  6(raebur 1063:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1065: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1066: 	     );
1.596.2.12.2.  6(raebur 1067:6):     &js_escape(\%js_lt);
          1(raebur 1068:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1069:     function checkSelect(checkBox) {
                   1070: 	var ctr=0;
                   1071: 	var sense="";
                   1072: 	if (checkBox.length > 1) {
                   1073: 	    for (var i=0; i<checkBox.length; i++) {
                   1074: 		if (checkBox[i].checked) {
                   1075: 		    ctr++;
                   1076: 		}
                   1077: 	    }
1.596.2.12.2.  6(raebur 1078:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng       1079: 	} else {
                   1080: 	    if (checkBox.checked) {
                   1081: 		ctr = 1;
                   1082: 	    }
1.596.2.12.2.  6(raebur 1083:6): 	    sense = '$js_lt{'single'}';
1.110     ng       1084: 	}
                   1085: 	if (ctr == 0) {
1.485     albertel 1086: 	    alert(sense);
1.110     ng       1087: 	    return false;
                   1088: 	}
                   1089: 	document.gradesub.submit();
                   1090:     }
                   1091: 
                   1092:     function reLoadList(formname) {
1.112     ng       1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1094: 	formname.command.value = 'submission';
                   1095: 	formname.submit();
                   1096:     }
1.45      ng       1097: LISTJAVASCRIPT
                   1098: 
1.118     ng       1099:     &commonJSfunctions($request);
1.41      ng       1100:     $request->print($result);
1.39      ng       1101: 
1.154     albertel 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel 1103: 	"\n".$table;
1.596.2.12.2.  1(raebur 1104:0): 
1.561     bisitz   1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                   1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1110:                   .&Apache::lonhtmlcommon::row_closure();
                   1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1115:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1116: 
1.442     banghart 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1119:     $env{'form.Status'} = $saveStatus;
1.596.2.12.2.  1(raebur 1120:0):     my %optiontext = &Apache::lonlocal::texthash (
                   1121:0):                           lastonly => 'last submission',
                   1122:0):                           last     => 'last submission with details',
                   1123:0):                           datesub  => 'all submissions',
                   1124:0):                           all      => 'all submissions with details',
                   1125:0):                       );
                   1126:0):     my $submission_options =
1.592     bisitz   1127:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1128:0):         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
                   1129:0):         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1130:         '<span class="LC_nobreak">'.
                   1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.596.2.12.2.  1(raebur 1132:0):         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1133:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1134:0):         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
                   1135:0):         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1136:         '<span class="LC_nobreak">'.
                   1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.596.2.12.2.  1(raebur 1138:0):         $optiontext{'all'}.'</label></span>';
                   1139:0):     my ($compmsg,$nocompmsg);
                   1140:0):     $nocompmsg = ' checked="checked"';
                   1141:0):     if ($numessay) {
                   1142:0):         $compmsg = $nocompmsg;
                   1143:0):         $nocompmsg = '';
                   1144:0):     }
1.561     bisitz   1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
1.596.2.12.2.  6(raebur 1146:1):                   .$submission_options;
                   1147:1): # Check if any gradable
                   1148:1):     my $showmore;
                   1149:1):     if ($perm{'mgr'}) {
                   1150:1):         my @sections;
                   1151:1):         if ($env{'request.course.sec'} ne '') {
                   1152:1):             @sections = ($env{'request.course.sec'});
          7(raebur 1153:1):         } elsif ($env{'form.section'} eq '') {
                   1154:1):             @sections = ('all');
          6(raebur 1155:1):         } else {
                   1156:1):             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1157:1):         }
                   1158:1):         if (grep(/^all$/,@sections)) {
                   1159:1):             $showmore = 1;
                   1160:1):         } else {
                   1161:1):             foreach my $sec (@sections) {
                   1162:1):                 if (&canmodify($sec)) {
                   1163:1):                     $showmore = 1;
                   1164:1):                     last;
                   1165:1):                 }
                   1166:1):             }
                   1167:1):         }
                   1168:1):     }
                   1169:1): 
                   1170:1):     if ($showmore) {
                   1171:1):         $gradeTable .=
                   1172:1):                    &Apache::lonhtmlcommon::row_closure()
          1(raebur 1173:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1174:0):                   .'<span class="LC_nobreak">'
                   1175:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1176:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1177:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1178:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1179:                   .&Apache::lonhtmlcommon::row_closure();
                   1180: 
1.596.2.12.2.  6(raebur 1181:1):         $gradeTable .= 
                   1182:1):                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1183:                   .'<select name="increment">'
                   1184:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1185:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1186:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1187:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1188:0):                   .'</select>';
          6(raebur 1189:1):     }
1.485     albertel 1190:     $gradeTable .= 
1.432     banghart 1191:         &build_section_inputs().
1.45      ng       1192: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1194: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1195:0):     if (exists($env{'form.Status'})) {
          7(raebur 1196:1): 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       1197:     } else {
1.596.2.12.2.  1(raebur 1198:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1199:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1200:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1201:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1202:     }
1.596.2.12.2.  1(raebur 1203:0):     if ($numessay) {
                   1204:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1205:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1206:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1207:0):     }
                   1208:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1209:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1210: 
                   1211:     $gradeTable .= '<p>'
1.596.2.12.2.  1(raebur 1212:0):                   .&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.")."\n"
1.561     bisitz   1213:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1214:                   .'</p>';
1.249     albertel 1215: 
                   1216: # checkall buttons
                   1217:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1218:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1219:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1220:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1221:     $gradeTable.=&check_buttons();
1.450     banghart 1222:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1223:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1224: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1225:     my $loop = 0;
                   1226:     while ($loop < 2) {
1.485     albertel 1227: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1228: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1229:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1230: 	    foreach my $part (sort(@$partlist)) {
                   1231: 		my $display_part=
                   1232: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1233: 		$gradeTable.=
                   1234: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1235: 	    }
1.301     albertel 1236: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1237: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1238: 	}
                   1239: 	$loop++;
1.126     ng       1240: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1241:     }
1.474     albertel 1242:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1243: 
1.45      ng       1244:     my $ctr = 0;
1.294     albertel 1245:     foreach my $student (sort 
                   1246: 			 {
                   1247: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1248: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1249: 			     }
                   1250: 			     return $a cmp $b;
                   1251: 			 }
                   1252: 			 (keys(%$fullname))) {
1.41      ng       1253: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1254: 
1.110     ng       1255: 	my %status = ();
1.301     albertel 1256: 
                   1257: 	if ($submitonly eq 'queued') {
                   1258: 	    my %queue_status = 
                   1259: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1260: 							$udom,$uname);
                   1261: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1262: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1263: 	}
                   1264: 
1.596.2.12.2.  1(raebur 1265:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1266: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1267: 	    my $submitted = 0;
1.164     albertel 1268: 	    my $graded = 0;
1.248     albertel 1269: 	    my $incorrect = 0;
1.110     ng       1270: 	    foreach (keys(%status)) {
1.145     albertel 1271: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1272: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1273: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1274: 		
1.110     ng       1275: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1276: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1277: 		    $submitted = 0;
1.150     albertel 1278: 		    my ($part)=split(/\./,$partid);
1.110     ng       1279: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1280: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1281: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1282: 		}
1.41      ng       1283: 	    }
1.248     albertel 1284: 	    
1.156     albertel 1285: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1286: 				     $submitonly eq 'incorrect' ||
                   1287: 				     $submitonly eq 'graded'));
1.248     albertel 1288: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1289: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1290: 	}
1.34      ng       1291: 
1.45      ng       1292: 	$ctr++;
1.249     albertel 1293: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1294:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1295: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1296: 	    if ($ctr%2 ==1) {
                   1297: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1298: 	    }
1.126     ng       1299: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1300:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1301:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1302: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1303: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1304: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1305: 
1.596.2.12.2.  1(raebur 1306:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1307: 		foreach (sort(keys(%status))) {
1.485     albertel 1308: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1309: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1310: 		}
1.41      ng       1311: 	    }
1.126     ng       1312: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1313: 	    if ($ctr%2 ==0) {
                   1314: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1315: 	    }
1.41      ng       1316: 	}
                   1317:     }
1.110     ng       1318:     if ($ctr%2 ==1) {
1.126     ng       1319: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1320:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1321: 		foreach (@$partlist) {
                   1322: 		    $gradeTable.='<td>&nbsp;</td>';
                   1323: 		}
1.301     albertel 1324: 	    } elsif ($submitonly eq 'queued') {
                   1325: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1326: 	    }
1.474     albertel 1327: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1328:     }
                   1329: 
1.474     albertel 1330:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1331:         '<input type="button" '.
                   1332:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1333:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1334:     if ($ctr == 0) {
1.96      albertel 1335: 	my $num_students=(scalar(keys(%$fullname)));
                   1336: 	if ($num_students eq 0) {
1.485     albertel 1337: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1338: 	} else {
1.171     albertel 1339: 	    my $submissions='submissions';
                   1340: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1341: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1342: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1343: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1344:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1345: 		    $num_students).
                   1346: 		'</span><br />';
1.96      albertel 1347: 	}
1.46      ng       1348:     } elsif ($ctr == 1) {
1.474     albertel 1349: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1350:     }
                   1351:     $request->print($gradeTable);
1.44      ng       1352:     return '';
1.10      ng       1353: }
                   1354: 
1.44      ng       1355: #---- Called from the listStudents routine
1.249     albertel 1356: 
                   1357: sub check_script {
1.596.2.12.2.  1(raebur 1358:0):     my ($form,$type) = @_;
                   1359:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1360:     function checkall() {
                   1361:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1362:             ele = document.forms.'.$form.'.elements[i];
                   1363:             if (ele.name == "'.$type.'") {
                   1364:             document.forms.'.$form.'.elements[i].checked=true;
                   1365:                                        }
                   1366:         }
                   1367:     }
                   1368: 
                   1369:     function checksec() {
                   1370:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1371:             ele = document.forms.'.$form.'.elements[i];
                   1372:            string = document.forms.'.$form.'.chksec.value;
                   1373:            if
                   1374:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1375:               document.forms.'.$form.'.elements[i].checked=true;
                   1376:             }
                   1377:         }
                   1378:     }
                   1379: 
                   1380: 
                   1381:     function uncheckall() {
                   1382:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1383:             ele = document.forms.'.$form.'.elements[i];
                   1384:             if (ele.name == "'.$type.'") {
                   1385:             document.forms.'.$form.'.elements[i].checked=false;
                   1386:                                        }
                   1387:         }
                   1388:     }
                   1389: 
1.596.2.12.2.  1(raebur 1390:0): '."\n");
1.249     albertel 1391:     return $chkallscript;
                   1392: }
                   1393: 
                   1394: sub check_buttons {
1.485     albertel 1395:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1396:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1397:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1398:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1399:     return $buttons;
                   1400: }
                   1401: 
1.44      ng       1402: #     Displays the submissions for one student or a group of students
1.34      ng       1403: sub processGroup {
1.596.2.12.2.  1(raebur 1404:0):     my ($request,$symb) = @_;
1.41      ng       1405:     my $ctr        = 0;
1.155     albertel 1406:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1407:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1408: 
1.396     banghart 1409:     foreach my $student (@stuchecked) {
                   1410: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1411: 	$env{'form.student'}        = $uname;
                   1412: 	$env{'form.userdom'}        = $udom;
                   1413: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1414:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1415: 	$ctr++;
                   1416:     }
                   1417:     return '';
1.35      ng       1418: }
1.34      ng       1419: 
1.44      ng       1420: #------------------------------------------------------------------------------------
                   1421: #
                   1422: #-------------------------- Next few routines handles grading by student, essentially
                   1423: #                           handles essay response type problem/part
                   1424: #
                   1425: #--- Javascript to handle the submission page functionality ---
                   1426: sub sub_page_js {
                   1427:     my $request = shift;
1.596.2.12.2.  6(raebur 1428:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1429:6):     &js_escape(\$alertmsg);
          1(raebur 1430:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1431:     function updateRadio(formname,id,weight) {
1.125     ng       1432: 	var gradeBox = formname["GD_BOX"+id];
                   1433: 	var radioButton = formname["RADVAL"+id];
                   1434: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1435: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1436: 	gradeBox.value = pts;
                   1437: 	var resetbox = false;
                   1438: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1439: 	    alert("$alertmsg"+pts);
1.71      ng       1440: 	    for (var i=0; i<radioButton.length; i++) {
                   1441: 		if (radioButton[i].checked) {
                   1442: 		    gradeBox.value = i;
                   1443: 		    resetbox = true;
                   1444: 		}
                   1445: 	    }
                   1446: 	    if (!resetbox) {
                   1447: 		formtextbox.value = "";
                   1448: 	    }
                   1449: 	    return;
1.44      ng       1450: 	}
1.71      ng       1451: 
                   1452: 	if (pts > weight) {
                   1453: 	    var resp = confirm("You entered a value ("+pts+
                   1454: 			       ") greater than the weight for the part. Accept?");
                   1455: 	    if (resp == false) {
1.125     ng       1456: 		gradeBox.value = oldpts;
1.71      ng       1457: 		return;
                   1458: 	    }
1.44      ng       1459: 	}
1.13      albertel 1460: 
1.71      ng       1461: 	for (var i=0; i<radioButton.length; i++) {
                   1462: 	    radioButton[i].checked=false;
                   1463: 	    if (pts == i && pts != "") {
                   1464: 		radioButton[i].checked=true;
                   1465: 	    }
                   1466: 	}
                   1467: 	updateSelect(formname,id);
1.125     ng       1468: 	formname["stores"+id].value = "0";
1.41      ng       1469:     }
1.5       albertel 1470: 
1.72      ng       1471:     function writeBox(formname,id,pts) {
1.125     ng       1472: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1473: 	if (checkSolved(formname,id) == 'update') {
                   1474: 	    gradeBox.value = pts;
                   1475: 	} else {
1.125     ng       1476: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1477: 	    gradeBox.value = oldpts;
1.125     ng       1478: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1479: 	    for (var i=0; i<radioButton.length; i++) {
                   1480: 		radioButton[i].checked=false;
1.72      ng       1481: 		if (i == oldpts) {
1.71      ng       1482: 		    radioButton[i].checked=true;
                   1483: 		}
                   1484: 	    }
1.41      ng       1485: 	}
1.125     ng       1486: 	formname["stores"+id].value = "0";
1.71      ng       1487: 	updateSelect(formname,id);
                   1488: 	return;
1.41      ng       1489:     }
1.44      ng       1490: 
1.71      ng       1491:     function clearRadBox(formname,id) {
                   1492: 	if (checkSolved(formname,id) == 'noupdate') {
                   1493: 	    updateSelect(formname,id);
                   1494: 	    return;
                   1495: 	}
1.125     ng       1496: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1497: 	for (var i=0; i<gradeSelect.length; i++) {
                   1498: 	    if (gradeSelect[i].selected) {
                   1499: 		var selectx=i;
                   1500: 	    }
                   1501: 	}
1.125     ng       1502: 	var stores = formname["stores"+id];
1.71      ng       1503: 	if (selectx == stores.value) { return };
1.125     ng       1504: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1505: 	gradeBox.value = "";
1.125     ng       1506: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1507: 	for (var i=0; i<radioButton.length; i++) {
                   1508: 	    radioButton[i].checked=false;
                   1509: 	}
                   1510: 	stores.value = selectx;
                   1511:     }
1.5       albertel 1512: 
1.71      ng       1513:     function checkSolved(formname,id) {
1.125     ng       1514: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1515: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1516: 	    if (!reply) {return "noupdate";}
1.120     ng       1517: 	    formname.overRideScore.value = 'yes';
1.41      ng       1518: 	}
1.71      ng       1519: 	return "update";
1.13      albertel 1520:     }
1.71      ng       1521: 
                   1522:     function updateSelect(formname,id) {
1.125     ng       1523: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1524: 	return;
1.41      ng       1525:     }
1.33      ng       1526: 
1.121     ng       1527: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1528:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1529: 	formname.gradeOpt.value = val;
1.71      ng       1530: 	if (val == "Save & Next") {
                   1531: 	    for (i=0;i<=total;i++) {
                   1532: 		for (j=0;j<parttot;j++) {
1.125     ng       1533: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1534: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1535: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1536: 			if (points == "") {
1.125     ng       1537: 			    var name = formname["name"+i].value;
1.129     ng       1538: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1539: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1540: 					       ", part "+partid+". Continue?");
1.71      ng       1541: 			    if (resp == false) {
1.125     ng       1542: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1543: 				return false;
                   1544: 			    }
                   1545: 			}
                   1546: 		    }
                   1547: 		}
                   1548: 	    }
                   1549: 	}
1.120     ng       1550: 	formname.submit();
                   1551:     }
                   1552: 
1.71      ng       1553: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1554:     function checkSubmitPage(formname,total) {
                   1555: 	noscore = new Array(100);
                   1556: 	var ptr = 0;
                   1557: 	for (i=1;i<total;i++) {
1.125     ng       1558: 	    var partid = formname["q_"+i].value;
1.127     ng       1559: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1560: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1561: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1562: 		if (points == "" && status != "correct_by_student") {
                   1563: 		    noscore[ptr] = i;
                   1564: 		    ptr++;
                   1565: 		}
                   1566: 	    }
                   1567: 	}
                   1568: 	if (ptr != 0) {
                   1569: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1570: 	    var prolist = "";
                   1571: 	    if (ptr == 1) {
                   1572: 		prolist = noscore[0];
                   1573: 	    } else {
                   1574: 		var i = 0;
                   1575: 		while (i < ptr-1) {
                   1576: 		    prolist += noscore[i]+", ";
                   1577: 		    i++;
                   1578: 		}
                   1579: 		prolist += "and "+noscore[i];
                   1580: 	    }
                   1581: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1582: 	    if (resp == false) {
                   1583: 		return false;
                   1584: 	    }
                   1585: 	}
1.45      ng       1586: 
1.71      ng       1587: 	formname.submit();
                   1588:     }
                   1589: SUBJAVASCRIPT
                   1590: }
1.45      ng       1591: 
1.596.2.12.2.  1(raebur 1592:0): #--- javascript for grading message center
                   1593:0): sub sub_grademessage_js {
1.71      ng       1594:     my $request = shift;
1.80      ng       1595:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1596:     &commonJSfunctions($request);
1.350     albertel 1597: 
1.596.2.12.2.  1(raebur 1598:0):     my $inner_js_msg_central= (<<INNERJS);
                   1599:0): <script type="text/javascript">
1.350     albertel 1600:     function checkInput() {
                   1601:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1602:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1603:       var usrctr = document.msgcenter.usrctr.value;
                   1604:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1605:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1606: 
                   1607:       var msgchk = "";
                   1608:       if (document.msgcenter.subchk.checked) {
                   1609:          msgchk = "msgsub,";
                   1610:       }
                   1611:       var includemsg = 0;
                   1612:       for (var i=1; i<=nmsg; i++) {
                   1613:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1614:           var frmmsg = document.msgcenter["msg"+i];
                   1615:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1616:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1617:           showflg.value = "1";
                   1618:           var chkbox = document.msgcenter["msgn"+i];
                   1619:           if (chkbox.checked) {
                   1620:              msgchk += "savemsg"+i+",";
                   1621:              includemsg = 1;
                   1622:           }
                   1623:       }
                   1624:       if (document.msgcenter.newmsgchk.checked) {
                   1625:          msgchk += "newmsg"+usrctr;
                   1626:          includemsg = 1;
                   1627:       }
                   1628:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1629:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1630:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1631:       includemsg.value = msgchk;
                   1632: 
                   1633:       self.close()
                   1634: 
                   1635:     }
1.351     albertel 1636: </script>
                   1637: INNERJS
                   1638: 
1.596.2.12.2.  1(raebur 1639:0):     my $start_page_msg_central =
1.351     albertel 1640:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1641: 				       {'js_ready'  => 1,
                   1642: 					'only_body' => 1,
                   1643: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1644:0):     my $end_page_msg_central =
1.351     albertel 1645: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1646: 
                   1647: 
1.219     www      1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1649:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1650:0): 
          6(raebur 1651:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1652:                 comp => 'Compose Message for: ',
                   1653:                 incl => 'Include',
                   1654:                 type => 'Type',
                   1655:                 subj => 'Subject',
                   1656:                 mesa => 'Message',
                   1657:                 new  => 'New',
                   1658:                 save => 'Save',
                   1659:                 canc => 'Cancel',
                   1660:              );
1.596.2.12.2.  6(raebur 1661:6):     &html_escape(\%html_js_lt);
                   1662:6):     &js_escape(\%html_js_lt);
          1(raebur 1663:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1664: 
                   1665: //===================== Script to view submitted by ==================
                   1666:   function viewSubmitter(submitter) {
                   1667:     document.SCORE.refresh.value = "on";
                   1668:     document.SCORE.NCT.value = "1";
                   1669:     document.SCORE.unamedom0.value = submitter;
                   1670:     document.SCORE.submit();
                   1671:     return;
                   1672:   }
                   1673: 
                   1674: //====================== Script for composing message ==============
1.80      ng       1675:    // preload images
                   1676:    img1 = new Image();
                   1677:    img1.src = "$iconpath/mailbkgrd.gif";
                   1678:    img2 = new Image();
                   1679:    img2.src = "$iconpath/mailto.gif";
                   1680: 
1.44      ng       1681:   function msgCenter(msgform,usrctr,fullname) {
                   1682:     var Nmsg  = msgform.savemsgN.value;
                   1683:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1684:     var subject = msgform.msgsub.value;
1.127     ng       1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1686:     re = /msgsub/;
                   1687:     var shwsel = "";
                   1688:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1690:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1691:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1692: 	var testmsg = "savemsg"+i+",";
                   1693: 	re = new RegExp(testmsg,"g");
1.44      ng       1694: 	shwsel = "";
                   1695: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1696: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1700:     }
1.125     ng       1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1702:     shwsel = "";
                   1703:     re = /newmsg/;
                   1704:     if (re.test(msgchk)) { shwsel = "checked" }
                   1705:     newMsg(newmsg,shwsel);
                   1706:     msgTail(); 
                   1707:     return;
                   1708:   }
                   1709: 
1.123     ng       1710:   function checkEntities(strx) {
                   1711:     if (strx.length == 0) return strx;
                   1712:     var orgStr = ["&", "<", ">", '"']; 
                   1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1714:     var counter = 0;
                   1715:     while (counter < 4) {
                   1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1717: 	counter++;
                   1718:     }
                   1719:     return strx;
                   1720:   }
                   1721: 
                   1722:   function strReplace(strx, orgStr, newStr) {
                   1723:     return strx.split(orgStr).join(newStr);
                   1724:   }
                   1725: 
1.44      ng       1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1727:     var height = 70*Nmsg+250;
1.44      ng       1728:     if (height > 600) {
                   1729: 	height = 600;
                   1730:     }
1.118     ng       1731:     var xpos = (screen.width-600)/2;
                   1732:     xpos = (xpos < 0) ? '0' : xpos;
                   1733:     var ypos = (screen.height-height)/2-30;
                   1734:     ypos = (ypos < 0) ? '0' : ypos;
                   1735: 
1.596.2.12.2.  (raeburn 1736:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1737:     pWin.focus();
                   1738:     pDoc = pWin.document;
1.219     www      1739:     pDoc.$docopen;
1.351     albertel 1740:     pDoc.write('$start_page_msg_central');
1.76      ng       1741: 
                   1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1744:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1745: 
1.596.2.12.2.  1(raebur 1746:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1747:0):     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1748: }
                   1749:     function displaySubject(msg,shwsel) {
1.76      ng       1750:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1751:0):     pDoc.write("<tr>");
1.465     albertel 1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1753:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1754:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1755: }
                   1756: 
1.72      ng       1757:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1758:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1759:0):     pDoc.write("<tr>");
1.465     albertel 1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1761:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1763: }
                   1764: 
                   1765:   function newMsg(newmsg,shwsel) {
1.76      ng       1766:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1767:0):     pDoc.write("<tr>");
1.465     albertel 1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1769:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1771: }
                   1772: 
                   1773:   function msgTail() {
1.76      ng       1774:     pDoc = pWin.document;
1.465     albertel 1775:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1776:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1777:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1778:     pDoc.write("<\\/form>");
1.351     albertel 1779:     pDoc.write('$end_page_msg_central');
1.128     ng       1780:     pDoc.close();
1.44      ng       1781: }
                   1782: 
1.596.2.12.2.  1(raebur 1783:0): SUBJAVASCRIPT
                   1784:0): }
                   1785:0): 
                   1786:0): #--- javascript for essay type problem --
                   1787:0): sub sub_page_kw_js {
                   1788:0):     my $request = shift;
                   1789:0): 
                   1790:0):     unless ($env{'form.compmsg'}) {
                   1791:0):         &commonJSfunctions($request);
                   1792:0):     }
                   1793:0): 
                   1794:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1795:0): <script type="text/javascript">
                   1796:0):     function updateChoice(flag) {
                   1797:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1798:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1799:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1800:0):       opener.document.SCORE.refresh.value = "on";
                   1801:0):       if (opener.document.SCORE.keywords.value!=""){
                   1802:0):          opener.document.SCORE.submit();
                   1803:0):       }
                   1804:0):       self.close()
                   1805:0):     }
                   1806:0): </script>
                   1807:0): INNERJS
                   1808:0): 
                   1809:0):     my $start_page_highlight_central =
                   1810:0):         &Apache::loncommon::start_page('Highlight Central',
                   1811:0):                                        $inner_js_highlight_central,
                   1812:0):                                        {'js_ready'  => 1,
                   1813:0):                                         'only_body' => 1,
                   1814:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1815:0):     my $end_page_highlight_central =
                   1816:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1817:0): 
                   1818:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1819:0):     $docopen=~s/^document\.//;
                   1820:0): 
                   1821:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1822:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1823:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1824:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1825:0):                 col1 => 'red',
                   1826:0):                 col2 => 'green',
                   1827:0):                 col3 => 'blue',
                   1828:0):                 siz1 => 'normal',
                   1829:0):                 siz2 => '+1',
                   1830:0):                 siz3 => '+2',
                   1831:0):                 sty1 => 'normal',
                   1832:0):                 sty2 => 'italic',
                   1833:0):                 sty3 => 'bold',
                   1834:0):              );
                   1835:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1836:0):                 save => 'Save',
                   1837:0):                 canc => 'Cancel',
                   1838:0):                 kehi => 'Keyword Highlight Options',
                   1839:0):                 txtc => 'Text Color',
                   1840:0):                 font => 'Font Size',
                   1841:0):                 fnst => 'Font Style',
                   1842:0):              );
                   1843:0):     &js_escape(\%js_lt);
                   1844:0):     &html_escape(\%html_js_lt);
                   1845:0):     &js_escape(\%html_js_lt);
                   1846:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1847:0): 
                   1848:0): //===================== Show list of keywords ====================
                   1849:0):   function keywords(formname) {
                   1850:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1851:0):     if (nret==null) return;
                   1852:0):     formname.keywords.value = nret;
                   1853:0): 
                   1854:0):     if (formname.keywords.value != "") {
                   1855:0):         formname.refresh.value = "on";
                   1856:0):         formname.submit();
                   1857:0):     }
                   1858:0):     return;
                   1859:0):   }
                   1860:0): 
                   1861:0): //===================== Script to add keyword(s) ==================
                   1862:0):   function getSel() {
                   1863:0):     if (document.getSelection) txt = document.getSelection();
                   1864:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1865:0):     else return;
                   1866:0):     if (typeof(txt) != 'string') {
                   1867:0):         txt = String(txt);
                   1868:0):     }
                   1869:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1870:0):     if (cleantxt=="") {
                   1871:0):         alert("$js_lt{'plse'}");
                   1872:0):         return;
                   1873:0):     }
                   1874:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1875:0):     if (nret==null) return;
                   1876:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1877:0):     if (document.SCORE.keywords.value != "") {
                   1878:0):         document.SCORE.refresh.value = "on";
                   1879:0):         document.SCORE.submit();
                   1880:0):     }
                   1881:0):     return;
                   1882:0):   }
                   1883:0): 
1.44      ng       1884: //====================== Script for keyword highlight options ==============
                   1885:   function kwhighlight() {
                   1886:     var kwclr    = document.SCORE.kwclr.value;
                   1887:     var kwsize   = document.SCORE.kwsize.value;
                   1888:     var kwstyle  = document.SCORE.kwstyle.value;
                   1889:     var redsel = "";
                   1890:     var grnsel = "";
                   1891:     var blusel = "";
1.596.2.12.2.  6(raebur 1892:6):     var txtcol1 = "$js_lt{'col1'}";
                   1893:6):     var txtcol2 = "$js_lt{'col2'}";
                   1894:6):     var txtcol3 = "$js_lt{'col3'}";
                   1895:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1896:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1897:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1898:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1899:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1900:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1901:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1902:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1903:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1904:     var sznsel = "";
                   1905:     var sz1sel = "";
                   1906:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1907:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1908:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1909:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1910:     var synsel = "";
                   1911:     var syisel = "";
                   1912:     var sybsel = "";
1.596.2.12.2.  8(raebur 1913:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1914:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1915:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1916:     highlightCentral();
1.596.2.12.2.  8(raebur 1917:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1918:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1919:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1920:     highlightend();
                   1921:     return;
                   1922:   }
                   1923: 
                   1924:   function highlightCentral() {
1.76      ng       1925: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1926:     var xpos = (screen.width-400)/2;
                   1927:     xpos = (xpos < 0) ? '0' : xpos;
                   1928:     var ypos = (screen.height-330)/2-30;
                   1929:     ypos = (ypos < 0) ? '0' : ypos;
                   1930: 
1.206     albertel 1931:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1932:     hwdWin.focus();
                   1933:     var hDoc = hwdWin.document;
1.219     www      1934:     hDoc.$docopen;
1.351     albertel 1935:     hDoc.write('$start_page_highlight_central');
1.76      ng       1936:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1937:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1938: 
1.596.2.12.2.  8(raebur 1939:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1940:6):     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1941:   }
                   1942: 
                   1943:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1944:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1945:4):     hDoc.write("<tr>");
1.76      ng       1946:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1947:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1948:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1949:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1950:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1951:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1952:     hDoc.write("<\\/tr>");
1.44      ng       1953:   }
                   1954: 
                   1955:   function highlightend() { 
1.76      ng       1956:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1957:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1958:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1959:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1960:     hDoc.write("<\\/form>");
1.351     albertel 1961:     hDoc.write('$end_page_highlight_central');
1.128     ng       1962:     hDoc.close();
1.44      ng       1963:   }
                   1964: 
                   1965: SUBJAVASCRIPT
                   1966: }
                   1967: 
1.349     albertel 1968: sub get_increment {
1.348     bowersj2 1969:     my $increment = $env{'form.increment'};
                   1970:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1971:         $increment != .1) {
                   1972:         $increment = 1;
                   1973:     }
                   1974:     return $increment;
                   1975: }
                   1976: 
1.585     bisitz   1977: sub gradeBox_start {
                   1978:     return (
                   1979:         &Apache::loncommon::start_data_table()
                   1980:        .&Apache::loncommon::start_data_table_header_row()
                   1981:        .'<th>'.&mt('Part').'</th>'
                   1982:        .'<th>'.&mt('Points').'</th>'
                   1983:        .'<th>&nbsp;</th>'
                   1984:        .'<th>'.&mt('Assign Grade').'</th>'
                   1985:        .'<th>'.&mt('Weight').'</th>'
                   1986:        .'<th>'.&mt('Grade Status').'</th>'
                   1987:        .&Apache::loncommon::end_data_table_header_row()
                   1988:     );
                   1989: }
                   1990: 
                   1991: sub gradeBox_end {
                   1992:     return (
                   1993:         &Apache::loncommon::end_data_table()
                   1994:     );
                   1995: }
1.71      ng       1996: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1997: sub gradeBox {
1.322     albertel 1998:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1999:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2000: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2001:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2002:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2003:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2004:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2005:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2006: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 2007:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2008:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2009:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2010: 				       [$partid]);
                   2011:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2012:     if ($last_resets{$partid}) {
                   2013:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2014:     }
1.596.2.12.2.  8(raebur 2015:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2016:     my $ctr = 0;
1.348     bowersj2 2017:     my $thisweight = 0;
1.349     albertel 2018:     my $increment = &get_increment();
1.485     albertel 2019: 
                   2020:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2021:     while ($thisweight<=$wgt) {
1.532     bisitz   2022: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2023:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2024: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2025: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2026: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2027:         $thisweight += $increment;
1.71      ng       2028: 	$ctr++;
                   2029:     }
1.485     albertel 2030:     $radio.='</tr></table>';
                   2031: 
                   2032:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2033: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2034: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2035: 	$wgt.')" /></td>'."\n";
1.485     albertel 2036:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2037: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2038: 	' </td>'."\n";
                   2039:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2040: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2041:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2042: 	$line.='<option></option>'.
                   2043: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2044:     } else {
1.485     albertel 2045: 	$line.='<option selected="selected"></option>'.
                   2046: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2047:     }
1.485     albertel 2048:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2049: 
                   2050: 
                   2051:     $result .= 
1.596.2.12.2.  8(raebur 2052:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2053:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2054:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2055:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2056: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2057: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2058: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2059:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2060:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2061:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2062:         $aggtries.'" />'."\n";
1.582     raeburn  2063:     my $res_error;
                   2064:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2065:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2066:     if ($res_error) {
                   2067:         return &navmap_errormsg();
                   2068:     }
1.318     banghart 2069:     return $result;
                   2070: }
1.322     albertel 2071: 
                   2072: sub handback_box {
1.596.2.12.2.  1(raebur 2073:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2074:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2075:0):     return unless ($numessay);
1.323     banghart 2076:     my (@respids);
1.596.2.4  raeburn  2077:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2078:     foreach my $part_response_id (@part_response_id) {
                   2079:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2080:         if ($part eq $partid) {
1.375     albertel 2081:             push(@respids,$resp);
1.323     banghart 2082:         }
                   2083:     }
1.318     banghart 2084:     my $result;
1.323     banghart 2085:     foreach my $respid (@respids) {
1.322     albertel 2086: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2087: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2088: 	next if (!@$files);
1.596.2.4  raeburn  2089: 	my $file_counter = 0;
1.313     banghart 2090: 	foreach my $file (@$files) {
1.368     banghart 2091: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2092:                 $file_counter++;
1.368     banghart 2093:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2094:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2095:     	        $file_disp = "$name.$ext";
                   2096:     	        $file = $file_path.$file_disp;
                   2097:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2098:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2099:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2100:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2101: 	    }
1.322     albertel 2102: 	}
1.596.2.4  raeburn  2103:         if ($file_counter) {
                   2104:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2105:                        '<span class="LC_info">'.
                   2106:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2107:         }
1.313     banghart 2108:     }
1.318     banghart 2109:     return $result;    
1.71      ng       2110: }
1.44      ng       2111: 
1.58      albertel 2112: sub show_problem {
1.382     albertel 2113:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2114:     my $rendered;
1.382     albertel 2115:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2116:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2117:     if ($mode eq 'both' or $mode eq 'text') {
                   2118: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2119: 						       $env{'request.course.id'},
                   2120: 						       undef,\%form);
1.144     albertel 2121:     }
1.58      albertel 2122:     if ($removeform) {
                   2123: 	$rendered=~s|<form(.*?)>||g;
                   2124: 	$rendered=~s|</form>||g;
1.374     albertel 2125: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2126:     }
1.144     albertel 2127:     my $companswer;
                   2128:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2129: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2130: 	$companswer=
                   2131: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2132: 						    $env{'request.course.id'},
                   2133: 						    %form);
1.144     albertel 2134:     }
1.58      albertel 2135:     if ($removeform) {
                   2136: 	$companswer=~s|<form(.*?)>||g;
                   2137: 	$companswer=~s|</form>||g;
1.144     albertel 2138: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2139:     }
1.596.2.12.2.  (raeburn 2140:):     my $renderheading = &mt('View of the problem');
                   2141:):     my $answerheading = &mt('Correct answer');
                   2142:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2143:):         my $stu_fullname = $env{'form.fullname'};
                   2144:):         if ($stu_fullname eq '') {
                   2145:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2146:):         }
                   2147:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2148:):         if ($forwhom ne '') {
                   2149:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2150:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2151:):         }
                   2152:):     }
1.468     albertel 2153:     $rendered=
1.588     bisitz   2154:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2155:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2156:        .$rendered
                   2157:        .'</div>';
1.468     albertel 2158:     $companswer=
1.588     bisitz   2159:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2160:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2161:        .$companswer
                   2162:        .'</div>';
1.468     albertel 2163:     my $result;
1.144     albertel 2164:     if ($mode eq 'both') {
1.588     bisitz   2165:         $result=$rendered.$companswer;
1.144     albertel 2166:     } elsif ($mode eq 'text') {
1.588     bisitz   2167:         $result=$rendered;
1.144     albertel 2168:     } elsif ($mode eq 'answer') {
1.588     bisitz   2169:         $result=$companswer;
1.144     albertel 2170:     }
1.71      ng       2171:     return $result;
1.58      albertel 2172: }
1.397     albertel 2173: 
1.396     banghart 2174: sub files_exist {
                   2175:     my ($r, $symb) = @_;
                   2176:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2177:     foreach my $student (@students) {
                   2178:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2179:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2180: 					      $udom,$uname);
1.596.2.12.2.  0.2.2(ra 2181:ar-23):         my ($string)= &get_last_submission(\%record);
1.397     albertel 2182:         foreach my $submission (@$string) {
                   2183:             my ($partid,$respid) =
                   2184: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2185:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2186: 					   \%record);
                   2187:             return 1 if (@$files);
1.396     banghart 2188:         }
                   2189:     }
1.397     albertel 2190:     return 0;
1.396     banghart 2191: }
1.397     albertel 2192: 
1.394     banghart 2193: sub download_all_link {
                   2194:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2195:0):     unless (&files_exist($r, $symb)) {
                   2196:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2197:0):         return;
                   2198:0):     }
1.395     albertel 2199:     my $all_students = 
                   2200: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2201: 
                   2202:     my $parts =
                   2203: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2204: 
1.394     banghart 2205:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2206:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2207:                              'cgi.'.$identifier.'.symb' => $symb,
                   2208:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2209:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2210: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2211:0):     return;
                   2212:0): }
                   2213:0): 
                   2214:0): sub submit_download_link {
                   2215:0):     my ($request,$symb) = @_;
                   2216:0):     if (!$symb) { return ''; }
                   2217:0):     my $res_error;
                   2218:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2219:0):         &response_type($symb,\$res_error);
                   2220:0):     if ($res_error) {
                   2221:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2222:0):         return;
                   2223:0):     }
                   2224:0):     unless ($numessay) {
                   2225:0):         $request->print(&mt('No essayresponse items found'));
                   2226:0):         return;
                   2227:0):     }
                   2228:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2229:0):     if (@chosenparts) {
                   2230:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2231:0):                                           undef,undef,1));
                   2232:0):     }
                   2233:0):     if ($numessay) {
                   2234:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2235:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2236:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2237:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2238:0):         if (ref($fullname) eq 'HASH') {
                   2239:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2240:0):             if (@students) {
                   2241:0):                 @{$env{'form.stuinfo'}} = @students;
                   2242:0):                 if ($numdropbox) {
                   2243:0):                     &download_all_link($request,$symb);
                   2244:0):                 } else {
                   2245:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2246:0):                 }
                   2247:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2248:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2249:0):             } else {
                   2250:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2251:0):             }
                   2252:0):         } else {
                   2253:0):             $request->print(&mt('Could not retrieve student information'));
                   2254:0):         }
                   2255:0):     } else {
                   2256:0):         $request->print(&mt('No essayresponse items found'));
                   2257:0):     }
                   2258:0):     return;
1.394     banghart 2259: }
1.395     albertel 2260: 
1.432     banghart 2261: sub build_section_inputs {
                   2262:     my $section_inputs;
                   2263:     if ($env{'form.section'} eq '') {
                   2264:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2265:     } else {
                   2266:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2267:         foreach my $section (@sections) {
1.432     banghart 2268:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2269:         }
                   2270:     }
                   2271:     return $section_inputs;
                   2272: }
                   2273: 
1.44      ng       2274: # --------------------------- show submissions of a student, option to grade 
                   2275: sub submission {
1.596.2.12.2.  1(raebur 2276:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2277:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2278:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2279:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2280:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2281:0): 
1.324     albertel 2282:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2283:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          5(raebur 2284:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2285: 
                   2286:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2287:4):         $request->print(
                   2288:4):             '<span class="LC_warning">'.
                   2289:4):             &mt('Unable to view requested student.').
                   2290:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2291:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2292:4):             '</span>');
1.104     albertel 2293: 	return;
                   2294:     }
                   2295: 
1.596.2.12.2.  1(raebur 2296:0):     my $res_error;
                   2297:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2298:0):         &response_type($symb,\$res_error);
                   2299:0):     if ($res_error) {
                   2300:0):         $request->print(&navmap_errormsg());
                   2301:0):         return;
                   2302:0):     }
                   2303:0): 
1.257     albertel 2304:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2305:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2306:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1.596.2.12.2.  1(raebur 2307:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2308:0):         $env{'form.compmsg'} = 1;
                   2309:0):     }
1.257     albertel 2310:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2311:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2312: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2313: 	'/check.gif" height="16" border="0" />';
1.41      ng       2314: 
                   2315:     # header info
                   2316:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2317:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2318:0):         if (@chosenparts) {
                   2319:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2320:0):         } elsif ($divforres) {
                   2321:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2322:0):         } else {
                   2323:0):             $request->print('<br clear="all" />');
                   2324:0):         }
1.41      ng       2325: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2326:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2327:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2328: 
1.44      ng       2329: 	# option to display problem, only once else it cause problems 
                   2330:         # with the form later since the problem has a form.
1.257     albertel 2331: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2332: 	    my $mode;
1.257     albertel 2333: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2334: 		$mode='both';
1.257     albertel 2335: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2336: 		$mode='text';
1.257     albertel 2337: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2338: 		$mode='answer';
                   2339: 	    }
1.329     albertel 2340: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2341: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2342: 	}
1.441     www      2343: 
1.41      ng       2344: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2345:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2346: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2347: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2348: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2349:0): 	}
                   2350:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2351:0): 	# if this subroutine has been called once.
                   2352:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2353: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2354: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2355: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2356: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2357: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2358:0): 	}
                   2359:0): 	if ($env{'form.compmsg'}) {
                   2360:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2361:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2362: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2363: 	}
1.596.2.12.2.  1(raebur 2364:0): 
1.257     albertel 2365: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2366: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2367: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2368: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2369: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2370: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2371: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2372: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2373: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2374: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2375: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2376: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2377: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2378:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2379: 			&build_section_inputs().
1.326     albertel 2380: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2381: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2382: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2383:0): 	if ($env{'form.compmsg'}) {
                   2384:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2385:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2386:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2387:0): 	}
                   2388:0): 	if ($numessay) {
1.257     albertel 2389: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2390: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2391: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2392:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2393: 	}
1.596.2.12.2.  1(raebur 2394:0): 
1.41      ng       2395: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2396: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2397: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2398: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2399: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2400: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2401: 		'" />'."\n".
                   2402: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2403: 	    $cts++;
                   2404: 	}
                   2405: 	$request->print($prnmsg);
1.32      ng       2406: 
1.596.2.12.2.  1(raebur 2407:0): 	if ($numessay) {
1.596.2.4  raeburn  2408: 
                   2409:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2410:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2411:                           keyw => 'Keyword Options',
                   2412:                           list => 'List',
                   2413:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2414:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2415:                      );
1.88      www      2416: #
                   2417: # Print out the keyword options line
                   2418: #
1.596.2.12.2.  1(raebur 2419:0): 	    $request->print(
          8(raebur 2420:4):                 '<div class="LC_columnSection">'
                   2421:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2422:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2423:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2424:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2425:4):  class="page">'.$lt{'past'}.'</a>',
                   2426:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2427:4):                     {legend => $lt{'keyw'}})
                   2428:4):                .'</fieldset></div>'
                   2429:4):             );
                   2430:4): 
1.88      www      2431: #
                   2432: # Load the other essays for similarity check
                   2433: #
1.596.2.12.2.  5(raebur 2434:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2435:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2436:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2437:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2438:9):                 if ($cdom ne '' && $cnum ne '') {
                   2439:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2440:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2441:9):                         my $apath = $1.'_'.$id;
                   2442:9):                         $apath=~s/\W/\_/gs;
                   2443:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2444:9):                     }
                   2445:9):                 }
                   2446:9):             } else {
                   2447:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2448:9): 	        $apath=&escape($apath);
                   2449:9): 	        $apath=~s/\W/\_/gs;
                   2450:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2451:9):             }
1.41      ng       2452:         }
                   2453:     }
1.44      ng       2454: 
1.441     www      2455: # This is where output for one specific student would start
1.592     bisitz   2456:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2457:     $request->print(
                   2458:         "\n\n"
                   2459:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2460:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2461:        ."\n"
                   2462:     );
1.441     www      2463: 
1.592     bisitz   2464:     # Show additional functions if allowed
                   2465:     if ($perm{'vgr'}) {
                   2466:         $request->print(
                   2467:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2468:3):                 'View recent activity',
1.592     bisitz   2469:                 $uname,$udom,'check')
                   2470:            .' '
                   2471:         );
                   2472:     }
                   2473:     if ($perm{'opa'}) {
                   2474:         $request->print(
                   2475:             &Apache::loncommon::pprmlink(
                   2476:                 &mt('Set/Change parameters'),
                   2477:                 $uname,$udom,$symb,'check'));
                   2478:     }
                   2479: 
                   2480:     # Show Problem
1.257     albertel 2481:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2482: 	my $mode;
1.257     albertel 2483: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2484: 	    $mode='both';
1.257     albertel 2485: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2486: 	    $mode='text';
1.257     albertel 2487: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2488: 	    $mode='answer';
                   2489: 	}
1.329     albertel 2490: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2491: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2492:     }
1.144     albertel 2493: 
1.257     albertel 2494:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2495: 
1.44      ng       2496:     # Display student info
1.41      ng       2497:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2498: 
                   2499:     my $result='<div class="LC_Box">'
                   2500:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2501:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2502:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  1(raebur 2503:0):     if ($numresp > $numessay) {
1.588     bisitz   2504:         $result.='<p class="LC_info">'
                   2505:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2506:                 ."</p>\n";
1.469     albertel 2507:     }
                   2508: 
1.596.2.12.2.  1(raebur 2509:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2510:     my $fullname;
                   2511:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2512:0):     if ($numessay) {
1.464     albertel 2513: 	(my $sub_result,$fullname,$col_fullnames)=
                   2514: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2515: 				 $counter);
                   2516: 	$result.=$sub_result;
1.41      ng       2517:     }
1.44      ng       2518:     $request->print($result."\n");
1.588     bisitz   2519: 
1.44      ng       2520:     # print student answer/submission
1.596.2.12.2.  1(raebur 2521:0):     # Options are (1) Last submission only
                   2522:0):     #             (2) Last submission (with detailed information for that submission)
                   2523:0):     #             (3) All transactions (by date)
                   2524:0):     #             (4) The whole record (with detailed information for all transactions)
                   2525:0): 
          0.2.2(ra 2526:ar-23):     my ($string,$timestamp,$lastgradetime,$lastsubmittime) = &get_last_submission(\%record);
          1(raebur 2527:0): 
                   2528:0):     my $lastsubonly;
                   2529:0): 
          0.2.2(ra 2530:ar-23):     if ($timestamp eq '') {
                   2531:ar-23):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$string->[0].'</div>'; 
          1(raebur 2532:0):     } else {
          0.2.2(ra 2533:ar-23):         my ($shownsubmdate,$showngradedate);
                   2534:ar-23):         if ($lastsubmittime && $lastgradetime) {
                   2535:ar-23):             $shownsubmdate = &Apache::lonlocal::locallocaltime($lastsubmittime);
                   2536:ar-23):             if ($lastgradetime > $lastsubmittime) {
                   2537:ar-23):                  $showngradedate = &Apache::lonlocal::locallocaltime($lastgradetime);
                   2538:ar-23):              }
                   2539:ar-23):         } else {
                   2540:ar-23):             $shownsubmdate = $timestamp;
                   2541:ar-23):         }
          1(raebur 2542:0):         $lastsubonly =
                   2543:0):             '<div class="LC_grade_submissions_body">'
          0.2.2(ra 2544:ar-23):            .'<b>'.&mt('Date Submitted:').'</b> '.$shownsubmdate."\n";
                   2545:ar-23):         if ($showngradedate) {
                   2546:ar-23):             $lastsubonly .= '<br /><b>'.&mt('Date Graded:').'</b> '.$showngradedate."\n";
                   2547:ar-23):         }
          1(raebur 2548:0): 
                   2549:0): 	my %seenparts;
                   2550:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2551:0): 	foreach my $part (@part_response_id) {
                   2552:0): 	    my ($partid,$respid) = @{ $part };
                   2553:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2554:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2555:0): 		if (exists($seenparts{$partid})) { next; }
                   2556:0): 		$seenparts{$partid}=1;
                   2557:0):                 $request->print(
                   2558:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2559:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2560:0):                                '<a href="javascript:viewSubmitter(\''.
                   2561:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2562:0):                                '\');" target="_self">'.
                   2563:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2564:0):                     '<br />');
                   2565:0): 		next;
                   2566:0): 	    }
                   2567:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2568:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2569:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2570:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2571:0):                     ' <span class="LC_internal_info">'.
                   2572:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2573:0):                     '</span>&nbsp; &nbsp;'.
                   2574:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2575:0): 		next;
                   2576:0): 	    }
                   2577:0): 	    foreach my $submission (@$string) {
                   2578:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2579:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2580:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2581:0): 		# Similarity check
                   2582:0):                 my $similar='';
                   2583:0):                 my ($type,$trial,$rndseed);
                   2584:0):                 if ($hide eq 'rand') {
                   2585:0):                     $type = 'randomizetry';
                   2586:0):                     $trial = $record{"resource.$partid.tries"};
                   2587:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2588:0):                 }
                   2589:0): 		if ($env{'form.checkPlag'}) {
                   2590:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2591:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2592:0): 		    if ($osim) {
                   2593:0): 		        $osim=int($osim*100.0);
                   2594:0):                         if ($hide eq 'anon') {
                   2595:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2596:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2597:0):                         } else {
                   2598:0): 			    $similar='<hr />';
                   2599:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2600:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2601:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2602:0):                                                 $osim,
                   2603:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2604:0):                                             '</span></h3>';
                   2605:0):                             } elsif ($ocrsid ne '') {
                   2606:0):                                 my %old_course_desc;
                   2607:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2608:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2609:9):                                 } else {
          1(raebur 2610:0):                                     my $args;
                   2611:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2612:0):                                         $args = {'one_time' => 1};
                   2613:0):                                     }
                   2614:0):                                     %old_course_desc =
                   2615:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2616:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2617:9):                                 }
          1(raebur 2618:0):                                 $similar .=
                   2619:0):                                     '<h3><span class="LC_warning">'.
                   2620:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2621:0): 				        $osim,
                   2622:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2623:0): 				        $old_course_desc{'description'},
                   2624:0): 				        $old_course_desc{'num'},
                   2625:0): 				        $old_course_desc{'domain'}).
                   2626:0): 				    '</span></h3>';
1.596     raeburn  2627:                             } else {
1.596.2.12.2.  1(raebur 2628:0):                                 $similar .=
                   2629:0):                                     '<h3><span class="LC_warning">'.
                   2630:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2631:0):                                         $osim,
                   2632:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2633:0):                                     '</span></h3>';
1.596     raeburn  2634:                             }
1.596.2.12.2.  1(raebur 2635:0):                             $similar .= '<blockquote><i>'.
                   2636:0):                                         &keywords_highlight($oessay).
                   2637:0):                                         '</i></blockquote><hr />';
                   2638:0): 		        }
                   2639:0):                     }
                   2640:0):                 }
                   2641:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2642:0):                                      undef,$type,$trial,$rndseed);
                   2643:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2644:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2645:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2646:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2647:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2648:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2649:0):                         ' <span class="LC_internal_info">'.
                   2650:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2651:0):                         '</span>&nbsp; &nbsp;';
                   2652:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2653:0): 		    if (@$files) {
1.596.2.2  raeburn  2654:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2655:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2656:                         } else {
1.596.2.12.2.  1(raebur 2657:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2658:0):                                          .'<br /><span class="LC_warning">';
                   2659:0):                             if(@$files == 1) {
                   2660:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2661:0):                             } else {
                   2662:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2663:4):                             }
          1(raebur 2664:0):                             $lastsubonly .= '</span>';
                   2665:0):                             foreach my $file (@$files) {
                   2666:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2667:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2668:4):                             }
1.596     raeburn  2669:                         }
1.596.2.12.2.  1(raebur 2670:0): 			$lastsubonly.='<br />';
1.41      ng       2671: 		    }
1.596.2.12.2.  1(raebur 2672:0):                     if ($hide eq 'anon') {
                   2673:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2674:0):                     } else {
                   2675:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2676:0):                         if ($draft) {
                   2677:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2678:0):                         }
                   2679:0):                         $subval =
                   2680:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2681:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2682:0):                         if ($responsetype eq 'essay') {
                   2683:0):                             $subval =~ s{\n}{<br />}g;
                   2684:0):                         }
                   2685:0):                         $lastsubonly.=$subval."\n";
                   2686:0):                     }
                   2687:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2688:0): 		    $lastsubonly.='</div>';
1.41      ng       2689: 		}
                   2690: 	    }
1.151     albertel 2691: 	}
1.596.2.12.2.  1(raebur 2692:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2693:0):     }
                   2694:0):     $request->print($lastsubonly);
                   2695:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2696:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2697: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2698:3):     }
                   2699:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2700:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2701: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2702: 								 $env{'request.course.id'},
1.44      ng       2703: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2704:5): 								 'Apache::grades::keywords_highlight',
                   2705:5):                                                                  $usec,$identifier));
1.41      ng       2706:     }
1.121     ng       2707:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2708: 	.$udom.'" />'."\n");
1.44      ng       2709:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2710:0):     if (!&canmodify($usec)) {
                   2711:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2712:0):         return;
1.180     albertel 2713:     } else {
1.468     albertel 2714: 	$request->print('</div>'."\n");
1.41      ng       2715:     }
1.33      ng       2716: 
1.596.2.12.2.  1(raebur 2717:0):     # grading message center
                   2718:0): 
                   2719:0):     if ($env{'form.compmsg'}) {
                   2720:0):         my $result='<div class="LC_Box">'.
                   2721:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2722:0):                    '<div class="LC_grade_message_center_body">';
                   2723:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2724:0):         my $msgfor = $givenn.' '.$lastname;
                   2725:0):         if (scalar(@$col_fullnames) > 0) {
                   2726:0):             my $lastone = pop(@$col_fullnames);
                   2727:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2728:0):         }
                   2729:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2730:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2731:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2732:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2733:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2734:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2735:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2736:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2737:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2738:0):                  '<br />&nbsp;('.
                   2739:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2740:0): 	         '</div></div>';
                   2741:0):         $request->print($result);
1.118     ng       2742:     }
1.41      ng       2743: 
                   2744:     my %seen = ();
                   2745:     my @partlist;
1.129     ng       2746:     my @gradePartRespid;
1.375     albertel 2747:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2748:     $request->print(
1.588     bisitz   2749:         '<div class="LC_Box">'
                   2750:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2751:     );
1.592     bisitz   2752:     $request->print(&gradeBox_start());
1.375     albertel 2753:     foreach my $part_response_id (@part_response_id) {
                   2754:     	my ($partid,$respid) = @{ $part_response_id };
                   2755: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2756: 	next if ($seen{$partid} > 0);
1.41      ng       2757: 	$seen{$partid}++;
1.524     raeburn  2758: 	push(@partlist,$partid);
                   2759: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2760: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2761:     }
1.585     bisitz   2762:     $request->print(&gradeBox_end()); # </div>
                   2763:     $request->print('</div>');
1.468     albertel 2764: 
                   2765:     $request->print('<div class="LC_grade_info_links">');
                   2766:     $request->print('</div>');
                   2767: 
1.45      ng       2768:     $result='<input type="hidden" name="partlist'.$counter.
                   2769: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2770:     $result.='<input type="hidden" name="gradePartRespid'.
                   2771: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2772:     my $ctr = 0;
                   2773:     while ($ctr < scalar(@partlist)) {
                   2774: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2775: 	    $partlist[$ctr].'" />'."\n";
                   2776: 	$ctr++;
                   2777:     }
1.468     albertel 2778:     $request->print($result.''."\n");
1.41      ng       2779: 
1.441     www      2780: # Done with printing info for one student
                   2781: 
1.468     albertel 2782:     $request->print('</div>');#LC_grade_show_user
1.441     www      2783: 
                   2784: 
1.41      ng       2785:     # print end of form
                   2786:     if ($counter == $total) {
1.592     bisitz   2787:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2788: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2789: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2790: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2791: 	my $ntstu ='<select name="NTSTU">'.
                   2792: 	    '<option>1</option><option>2</option>'.
                   2793: 	    '<option>3</option><option>5</option>'.
                   2794: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2795: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2796: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2797:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2798: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2799: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2800: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2801: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2802:         $endform.='<span class="LC_warning">'.
                   2803:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2804:                   '</span>'."\n" ;
1.349     albertel 2805:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2806:             "' name='increment' />";
1.485     albertel 2807: 	$endform.='</td></tr></table></form>';
1.41      ng       2808: 	$request->print($endform);
                   2809:     }
                   2810:     return '';
1.38      ng       2811: }
                   2812: 
1.464     albertel 2813: sub check_collaborators {
                   2814:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2815:     my ($result,@col_fullnames);
                   2816:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2817:     foreach my $part (keys(%$handgrade)) {
                   2818: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2819: 					'.maxcollaborators',
                   2820: 					$symb,$udom,$uname);
                   2821: 	next if ($ncol <= 0);
                   2822: 	$part =~ s/\_/\./g;
                   2823: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2824: 	my (@good_collaborators, @bad_collaborators);
                   2825: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2826: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2827: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2828: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2829: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2830: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2831: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2832: 	    # Doing this grep allows 'fuzzy' specification
                   2833: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2834: 			       keys(%$classlist));
                   2835: 	    if (! scalar(@matches)) {
                   2836: 		push(@bad_collaborators, $possible_collaborator);
                   2837: 	    } else {
                   2838: 		push(@good_collaborators, @matches);
                   2839: 	    }
                   2840: 	}
                   2841: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2842: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2843: 	    foreach my $name (@good_collaborators) {
                   2844: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2845: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2846: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2847: 	    }
1.596.2.4  raeburn  2848: 	    $result.='</ol><br />'."\n";
1.466     albertel 2849: 	    my ($part)=split(/\./,$part);
1.464     albertel 2850: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2851: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2852: 		"\n";
                   2853: 	}
                   2854: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2855: 	    $result.='<div class="LC_warning">';
1.464     albertel 2856: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2857: 	    $result .= '</div>';
                   2858: 	}         
                   2859: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2860: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2861: 	    $result .= &mt('This student has submitted too many '.
                   2862: 		'collaborators.  Maximum is [_1].',$ncol);
                   2863: 	    $result .= '</div>';
                   2864: 	}
                   2865:     }
                   2866:     return ($result,$fullname,\@col_fullnames);
                   2867: }
                   2868: 
1.44      ng       2869: #--- Retrieve the last submission for all the parts
1.38      ng       2870: sub get_last_submission {
1.119     ng       2871:     my ($returnhash)=@_;
1.596.2.12.2.  0.2.2(ra 2872:ar-23):     my (@string,$timestamp,$lastgradetime,$lastsubmittime);
1.119     ng       2873:     if ($$returnhash{'version'}) {
1.46      ng       2874: 	my %lasthash=();
1.596.2.12.2.  0.2.2(ra 2875:ar-23):         my %prevsolved=();
                   2876:ar-23):         my %solved=();
                   2877:ar-23): 	my $version;
1.119     ng       2878: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.596.2.12.2.  0.2.2(ra 2879:ar-23):             my %handgraded = ();
1.397     albertel 2880: 	    foreach my $key (sort(split(/\:/,
                   2881: 					$$returnhash{$version.':keys'}))) {
                   2882: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
1.596.2.12.2.  0.2.2(ra 2883:ar-23):                 if ($key =~ /\.([^.]+)\.regrader$/) {
                   2884:ar-23):                     $handgraded{$1} = 1;
                   2885:ar-23):                 } elsif ($key =~ /\.portfiles$/) {
                   2886:ar-23):                     if (($$returnhash{$version.':'.$key} ne '') &&
                   2887:ar-23):                         ($$returnhash{$version.':'.$key} !~ /\.\d+\.\w+$/)) {
                   2888:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2889:ar-23):                     }
                   2890:ar-23):                 } elsif ($key =~ /\.submission$/) {
                   2891:ar-23):                     if ($$returnhash{$version.':'.$key} ne '') {
                   2892:ar-23):                         $lastsubmittime = $$returnhash{$version.':timestamp'};
                   2893:ar-23):                     }
                   2894:ar-23):                 } elsif ($key =~ /\.([^.]+)\.solved$/) {
                   2895:ar-23):                     $prevsolved{$1} = $solved{$1};
                   2896:ar-23):                     $solved{$1} = $lasthash{$key};
                   2897:ar-23):                 }
          0.2.3(ra 2898:ar-23):             }
          0.2.2(ra 2899:ar-23):             foreach my $partid (keys(%handgraded)) {
                   2900:ar-23):                 if (($prevsolved{$partid} eq 'ungraded_attempted') &&
                   2901:ar-23):                     (($solved{$partid} eq 'incorrect_by_override') ||
                   2902:ar-23):                      ($solved{$partid} eq 'correct_by_override'))) {
                   2903:ar-23):                     $lastgradetime = $$returnhash{$version.':timestamp'};
                   2904:ar-23):                 }
                   2905:ar-23):                 if ($solved{$partid} ne '') {
                   2906:ar-23):                     $prevsolved{$partid} = $solved{$partid};
                   2907:ar-23):                 }
                   2908:ar-23):             }
                   2909:ar-23): 	    $timestamp = 
                   2910:ar-23): 		&Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2911: 	}
1.596.2.2  raeburn  2912:         my (%typeparts,%randombytry);
1.596     raeburn  2913:         my $showsurv = 
                   2914:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2915:         foreach my $key (sort(keys(%lasthash))) {
                   2916:             if ($key =~ /\.type$/) {
                   2917:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2918:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2919:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2920:                     my ($ign,@parts) = split(/\./,$key);
                   2921:                     pop(@parts);
1.596.2.3  raeburn  2922:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2923:                     if ($lasthash{$key} eq 'randomizetry') {
                   2924:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2925:                     } else {
                   2926:                         unless ($showsurv) {
                   2927:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2928:                         }
1.596     raeburn  2929:                     }
                   2930:                     delete($lasthash{$key});
                   2931:                 }
                   2932:             }
                   2933:         }
                   2934:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2935:         my @randomize = keys(%randombytry);
1.397     albertel 2936: 	foreach my $key (keys(%lasthash)) {
                   2937: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2938:             my $hide;
                   2939:             if (@hidden) {
                   2940:                 foreach my $id (@hidden) {
                   2941:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2942:                         $hide = 'anon';
1.596     raeburn  2943:                         last;
                   2944:                     }
                   2945:                 }
                   2946:             }
1.596.2.2  raeburn  2947:             unless ($hide) {
                   2948:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2949:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2950:                         if ($key =~ /^\Q$id\E/) {
                   2951:                             $hide = 'rand';
                   2952:                             last;
                   2953:                         }
                   2954:                     }
                   2955:                 }
                   2956:             }
1.397     albertel 2957: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2958:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2959:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2960:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2961:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2962: 	}
                   2963:     }
1.397     albertel 2964:     if (!@string) {
                   2965: 	$string[0] =
1.539     riegler  2966: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2967:     }
1.596.2.12.2.  0.2.2(ra 2968:ar-23):     return (\@string,$timestamp,$lastgradetime,$lastsubmittime);
1.38      ng       2969: }
1.35      ng       2970: 
1.44      ng       2971: #--- High light keywords, with style choosen by user.
1.38      ng       2972: sub keywords_highlight {
1.44      ng       2973:     my $string    = shift;
1.257     albertel 2974:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2975:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2976:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2977:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2978:     foreach my $keyword (@keylist) {
                   2979: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2980:     }
                   2981:     return $string;
1.38      ng       2982: }
1.36      ng       2983: 
1.596.2.12.2.  (raeburn 2984:): # For Tasks provide a mechanism to display previous version for one specific student
                   2985:): 
                   2986:): sub show_previous_task_version {
                   2987:):     my ($request,$symb) = @_;
                   2988:):     if ($symb eq '') {
          8(raebur 2989:4):         $request->print(
                   2990:4):             '<span class="LC_error">'.
                   2991:4):             &mt('Unable to handle ambiguous references.').
                   2992:4):             '</span>');
          (raeburn 2993:):         return '';
                   2994:):     }
                   2995:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2996:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2997:):     if (!&canview($usec)) {
          8(raebur 2998:4):         $request->print('<span class="LC_warning">'.
                   2999:4):                         &mt('Unable to view previous version for requested student.').
                   3000:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 3001:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 3002:4):                         '</span>');
          (raeburn 3003:):         return;
                   3004:):     }
                   3005:):     my $mode = 'both';
                   3006:):     my $isTask = ($symb =~/\.task$/);
                   3007:):     if ($isTask) {
                   3008:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   3009:):             if ($env{'form.fullname'} eq '') {
                   3010:):                 $env{'form.fullname'} =
                   3011:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   3012:):             }
                   3013:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   3014:):             $request->print("\n\n".
                   3015:):                             '<div class="LC_grade_show_user">'.
                   3016:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   3017:):                             '</h2>'."\n");
                   3018:):             &Apache::lonxml::clear_problem_counter();
                   3019:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   3020:):                             {'previousversion' => $env{'form.previousversion'} }));
                   3021:):             $request->print("\n</div>");
                   3022:):         }
                   3023:):     }
                   3024:):     return;
                   3025:): }
                   3026:): 
                   3027:): sub choose_task_version_form {
                   3028:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   3029:):     my $isTask = ($symb =~/\.task$/);
                   3030:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3031:):     if ($isTask) {
                   3032:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3033:):                                               $udom,$uname);
                   3034:):         if (($record{'resource.0.version'} eq '') ||
                   3035:):             ($record{'resource.0.version'} < 2)) {
                   3036:):             return ($record{'resource.0.version'},
                   3037:):                     $record{'resource.0.version'},$result,$js);
                   3038:):         } else {
                   3039:):             $current = $record{'resource.0.version'};
                   3040:):         }
                   3041:):         if ($env{'form.previousversion'}) {
                   3042:):             $displayed = $env{'form.previousversion'};
                   3043:):             $rowtitle = &mt('Choose another version:')
                   3044:):         } else {
                   3045:):             $displayed = $current;
                   3046:):             $rowtitle = &mt('Show earlier version:');
                   3047:):         }
                   3048:):         $result = '<div class="LC_left_float">';
                   3049:):         my $list;
                   3050:):         my $numversions = 0;
                   3051:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3052:):             if ($i == $current) {
                   3053:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3054:):                     next;
                   3055:):                 } else {
                   3056:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3057:):                     $numversions ++;
                   3058:):                 }
                   3059:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3060:):                 unless ($i == $env{'form.previousversion'}) {
                   3061:):                     $numversions ++;
                   3062:):                 }
                   3063:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3064:):             }
                   3065:):         }
                   3066:):         if ($numversions) {
                   3067:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3068:):             $result .=
                   3069:):                 '<form name="getprev" method="post" action=""'.
                   3070:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3071:):                 &Apache::loncommon::start_data_table().
                   3072:):                 &Apache::loncommon::start_data_table_row().
                   3073:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3074:):                 '<td><select name="version">'.
                   3075:):                 '<option>'.&mt('Select').'</option>'.
                   3076:):                 $list.
                   3077:):                 '</select></td>'.
                   3078:):                 &Apache::loncommon::end_data_table_row();
                   3079:):             unless ($nomenu) {
                   3080:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3081:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3082:):                 '<td><span class="LC_nobreak">'.
                   3083:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3084:):                 &mt('Yes').'</label>'.
                   3085:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3086:):                 '</span></td>'.
                   3087:):                 &Apache::loncommon::end_data_table_row();
                   3088:):             }
                   3089:):             $result .=
                   3090:):                 &Apache::loncommon::start_data_table_row().
                   3091:):                 '<th align="left">&nbsp;</th>'.
                   3092:):                 '<td>'.
                   3093:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3094:):                 '</td>'.
                   3095:):                 &Apache::loncommon::end_data_table_row().
                   3096:):                 &Apache::loncommon::end_data_table().
                   3097:):                 '</form>';
                   3098:):             $js = &previous_display_javascript($nomenu,$current);
                   3099:):         } elsif ($displayed && $nomenu) {
                   3100:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3101:):         } else {
                   3102:):             $result .= &mt('No previous versions to show for this student');
                   3103:):         }
                   3104:):         $result .= '</div>';
                   3105:):     }
                   3106:):     return ($current,$displayed,$result,$js);
                   3107:): }
                   3108:): 
                   3109:): sub previous_display_javascript {
                   3110:):     my ($nomenu,$current) = @_;
                   3111:):     my $js = <<"JSONE";
                   3112:): <script type="text/javascript">
                   3113:): // <![CDATA[
                   3114:): function previousVersion(uname,udom,symb) {
                   3115:):     var current = '$current';
                   3116:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3117:):     var prevstr = new RegExp("^\\\\d+\$");
                   3118:):     if (!prevstr.test(version)) {
                   3119:):         return false;
                   3120:):     }
                   3121:):     var url = '';
                   3122:):     if (version == current) {
                   3123:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3124:):     } else {
                   3125:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3126:):     }
                   3127:): JSONE
                   3128:):     if ($nomenu) {
                   3129:):         $js .= <<"JSTWO";
                   3130:):     document.location.href = url;
                   3131:): JSTWO
                   3132:):     } else {
                   3133:):         $js .= <<"JSTHREE";
                   3134:):     var newwin = 0;
                   3135:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3136:):         if (document.getprev.prevwin[i].checked == true) {
                   3137:):             newwin = document.getprev.prevwin[i].value;
                   3138:):         }
                   3139:):     }
                   3140:):     if (newwin == 1) {
                   3141:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3142:):         url = url+'&inhibitmenu=yes';
                   3143:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3144:):             previousWin = window.open(url,'',options,1);
                   3145:):         } else {
                   3146:):             previousWin.location.href = url;
                   3147:):         }
                   3148:):         previousWin.focus();
                   3149:):         return false;
                   3150:):     } else {
                   3151:):         document.location.href = url;
                   3152:):         return false;
                   3153:):     }
                   3154:): JSTHREE
                   3155:):     }
                   3156:):     $js .= <<"ENDJS";
                   3157:):     return false;
                   3158:): }
                   3159:): // ]]>
                   3160:): </script>
                   3161:): ENDJS
                   3162:): 
                   3163:): }
                   3164:): 
1.44      ng       3165: #--- Called from submission routine
1.38      ng       3166: sub processHandGrade {
1.596.2.12.2.  1(raebur 3167:0):     my ($request,$symb) = @_;
1.324     albertel 3168:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3169:     my $button = $env{'form.gradeOpt'};
                   3170:     my $ngrade = $env{'form.NCT'};
                   3171:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3172:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3173:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  8(raebur 3174:1):     my ($res_error,%queueable);
                   3175:1):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3176:1):     if ($res_error) {
                   3177:1):         $request->print(&navmap_errormsg());
                   3178:1):         return;
                   3179:1):     } else {
                   3180:1):         foreach my $part (@{$partlist}) {
                   3181:1):             if (ref($responseType->{$part}) eq 'HASH') {
                   3182:1):                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3183:1):                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3184:1):                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3185:1):                         $queueable{$part} = 1;
                   3186:1):                         last;
                   3187:1):                     }
                   3188:1):                 }
                   3189:1):             }
                   3190:1):         }
                   3191:1):     }
1.301     albertel 3192: 
1.44      ng       3193:     if ($button eq 'Save & Next') {
                   3194: 	my $ctr = 0;
                   3195: 	while ($ctr < $ngrade) {
1.257     albertel 3196: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3197:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
          8(raebur 3198:1):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3199: 	    if ($errorflag eq 'no_score') {
                   3200: 		$ctr++;
                   3201: 		next;
                   3202: 	    }
1.104     albertel 3203: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3204:4):                 $request->print(
                   3205:4):                     '<span class="LC_error">'
                   3206:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3207:4):                    .'</span>');
1.104     albertel 3208: 		$ctr++;
                   3209: 		next;
                   3210: 	    }
1.596.2.12.2.  1(raebur 3211:5):             if ($numhidden) {
                   3212:5):                 $request->print(
                   3213:5):                     '<span class="LC_info">'
                   3214:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3215:5):                    .'</span><br />');
                   3216:5):             }
1.257     albertel 3217: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3218: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3219: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3220:             my ($feedurl,$showsymb) =
                   3221: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3222: 	    my $messagetail;
1.62      albertel 3223: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3224: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3225: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3226: 		$subject.=' ['.$restitle.']';
1.44      ng       3227: 		my (@msgnum) = split(/,/,$includemsg);
                   3228: 		foreach (@msgnum) {
1.257     albertel 3229: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3230: 		}
1.80      ng       3231: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3232: 		if ($env{'form.withgrades'.$ctr}) {
                   3233: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3234: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3235:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3236: 		}
                   3237: 		$msgstatus = 
                   3238:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3239: 						     $message.$messagetail,
1.418     albertel 3240:                                                      undef,$feedurl,undef,
1.386     raeburn  3241:                                                      undef,undef,$showsymb,
                   3242:                                                      $restitle);
1.574     bisitz   3243: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3244: 				$msgstatus.'<br />');
1.44      ng       3245: 	    }
1.257     albertel 3246: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3247: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3248: 		foreach my $collabstr (@collabstrs) {
                   3249: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3250: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3251: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3252: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.596.2.12.2.  8(raebur 3253:1): 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3254: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3255: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3256: 			    next;
1.418     albertel 3257: 			} elsif ($message ne '') {
                   3258: 			    my ($baseurl,$showsymb) = 
                   3259: 				&get_feedurl_and_symb($symb,$collaborator,
                   3260: 						      $udom);
                   3261: 			    if ($env{'form.withgrades'.$ctr}) {
                   3262: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3263:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3264: 			    }
1.418     albertel 3265: 			    $msgstatus = 
                   3266: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3267: 			}
1.44      ng       3268: 		    }
                   3269: 		}
                   3270: 	    }
                   3271: 	    $ctr++;
                   3272: 	}
                   3273:     }
                   3274: 
1.596.2.12.2.  1(raebur 3275:0):     my %keyhash = ();
                   3276:0):     if ($numessay) {
1.119     ng       3277: 	# Keywords sorted in alphabatical order
1.257     albertel 3278: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3279: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3280:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3281: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3282: 	$env{'form.keywords'} = join(' ',@keywords);
                   3283: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3284: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3285: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3286: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3287: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3288:0):     }
1.119     ng       3289: 
1.596.2.12.2.  1(raebur 3290:0):     if ($env{'form.compmsg'}) {
1.119     ng       3291: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3292: 	# New messages are saved in env for the next student.
1.119     ng       3293: 	# All messages are saved in nohist_handgrade.db
                   3294: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3295: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3296: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3297: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3298: 		$idx++;
                   3299: 	    }
                   3300: 	    $ctr++;
1.41      ng       3301: 	}
1.119     ng       3302: 	$ctr = 0;
                   3303: 	while ($ctr < $ngrade) {
1.257     albertel 3304: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3305: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3306: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3307: 		$idx++;
                   3308: 	    }
                   3309: 	    $ctr++;
1.41      ng       3310: 	}
1.257     albertel 3311: 	$env{'form.savemsgN'} = --$idx;
                   3312: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3313:0):     }
                   3314:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3315: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3316: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3317:     }
1.596.2.12.2.  1(raebur 3318:0): 
1.44      ng       3319:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3320:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3321:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3322: 	my ($ctr,$total) = (0,0);
                   3323: 	while ($ctr < $ngrade) {
1.257     albertel 3324: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3325: 	    $ctr++;
                   3326: 	}
1.257     albertel 3327: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3328: 	$ctr = 0;
                   3329: 	while ($ctr < $total) {
1.257     albertel 3330: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3331: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3332: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3333:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3334: 	    $ctr++;
                   3335: 	}
                   3336: 	return '';
                   3337:     }
1.36      ng       3338: 
1.44      ng       3339:     # Get the next/previous one or group of students
1.257     albertel 3340:     my $firststu = $env{'form.unamedom0'};
                   3341:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3342:     my $ctr = 2;
1.41      ng       3343:     while ($laststu eq '') {
1.257     albertel 3344: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3345: 	$ctr++;
                   3346: 	$laststu = $firststu if ($ctr > $ngrade);
                   3347:     }
1.44      ng       3348: 
1.41      ng       3349:     my (@parsedlist,@nextlist);
                   3350:     my ($nextflg) = 0;
1.524     raeburn  3351:     foreach my $item (sort 
1.294     albertel 3352: 	     {
                   3353: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3354: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3355: 		 }
                   3356: 		 return $a cmp $b;
                   3357: 	     } (keys(%$fullname))) {
1.41      ng       3358: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3359: 	    push(@parsedlist,$item);
1.41      ng       3360: 	}
1.524     raeburn  3361: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3362: 	if ($button eq 'Previous') {
1.524     raeburn  3363: 	    last if ($item eq $firststu);
                   3364: 	    push(@parsedlist,$item);
1.41      ng       3365: 	}
                   3366:     }
                   3367:     $ctr = 0;
                   3368:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3369:     foreach my $student (@parsedlist) {
1.257     albertel 3370: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3371: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3372: 	
                   3373: 	if ($submitonly eq 'queued') {
                   3374: 	    my %queue_status = 
                   3375: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3376: 							$udom,$uname);
                   3377: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3378: 	}
                   3379: 
1.156     albertel 3380: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3381: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3382: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3383: 	    my $submitted = 0;
1.248     albertel 3384: 	    my $ungraded = 0;
                   3385: 	    my $incorrect = 0;
1.524     raeburn  3386: 	    foreach my $item (keys(%status)) {
                   3387: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3388: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3389: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3390: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3391: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3392: 		    $submitted = 0;
                   3393: 		}
1.41      ng       3394: 	    }
1.156     albertel 3395: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3396: 				     $submitonly eq 'incorrect' ||
                   3397: 				     $submitonly eq 'graded'));
1.248     albertel 3398: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3399: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3400: 	}
1.524     raeburn  3401: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3402: 	last if ($ctr == $ntstu);
1.41      ng       3403: 	$ctr++;
                   3404:     }
1.36      ng       3405: 
1.41      ng       3406:     $ctr = 0;
                   3407:     my $total = scalar(@nextlist)-1;
1.39      ng       3408: 
1.524     raeburn  3409:     foreach (sort(@nextlist)) {
1.41      ng       3410: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3411: 	$env{'form.student'}  = $uname;
                   3412: 	$env{'form.userdom'}  = $udom;
                   3413: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3414:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3415: 	$ctr++;
                   3416:     }
                   3417:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3418:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3419: 	$request->print($the_end);
                   3420:     }
                   3421:     return '';
1.38      ng       3422: }
1.36      ng       3423: 
1.44      ng       3424: #---- Save the score and award for each student, if changed
1.38      ng       3425: sub saveHandGrade {
1.596.2.12.2.  8(raebur 3426:1):     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3427:     my @version_parts;
1.104     albertel 3428:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3429: 					   $env{'request.course.id'});
1.104     albertel 3430:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3431:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3432:     my @parts_graded;
1.77      ng       3433:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3434:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3435:     my %aggregate = ();
                   3436:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3437:5):     if ($env{'form.HIDE'.$newflg}) {
                   3438:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3439:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3440:5):         $totchg += $numchgs;
                   3441:5):     }
1.301     albertel 3442:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3443:     foreach my $new_part (@parts) {
1.337     banghart 3444: 	#collaborator ($submi may vary for different parts
1.259     banghart 3445: 	if ($submitter && $new_part ne $part) { next; }
                   3446: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3447: 	if ($dropMenu eq 'excused') {
1.259     banghart 3448: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3449: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3450: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3451: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3452: 		}
1.364     banghart 3453: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3454: 	    }
1.125     ng       3455: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3456: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3457: 	    foreach my $key (keys(%record)) {
1.259     banghart 3458: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3459: 	    }
1.259     banghart 3460: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3461: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3462:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3463: 
                   3464:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3465: 					       [$new_part]);
                   3466:             my $aggtries =$totaltries;
1.269     raeburn  3467:             if ($last_resets{$new_part}) {
1.270     albertel 3468:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3469: 					   $new_part);
1.269     raeburn  3470:             }
1.270     albertel 3471: 
                   3472:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3473:             if ($aggtries > 0) {
1.327     albertel 3474:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3475:                 $aggregateflag = 1;
                   3476:             }
1.125     ng       3477: 	} elsif ($dropMenu eq '') {
1.259     banghart 3478: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3479: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3480: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3481: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3482: 		next;
                   3483: 	    }
1.259     banghart 3484: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3485: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3486: 	    my $partial= $pts/$wgt;
1.259     banghart 3487: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3488: 		#do not update score for part if not changed.
1.346     banghart 3489:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3490: 		next;
1.251     banghart 3491: 	    } else {
1.524     raeburn  3492: 	        push(@parts_graded,$new_part);
1.153     albertel 3493: 	    }
1.259     banghart 3494: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3495: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3496: 	    }
1.259     banghart 3497: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3498: 	    if ($partial == 0) {
1.153     albertel 3499: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3500: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3501: 		}
1.41      ng       3502: 	    } else {
1.153     albertel 3503: 		if ($record{$reckey} ne 'correct_by_override') {
                   3504: 		    $newrecord{$reckey} = 'correct_by_override';
                   3505: 		}
                   3506: 	    }	    
                   3507: 	    if ($submitter && 
1.259     banghart 3508: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3509: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3510: 	    }
1.259     banghart 3511: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3512: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3513: 	}
1.259     banghart 3514: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3515: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3516: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3517: 	        $dropMenu eq 'reset status')
                   3518: 	   {
1.524     raeburn  3519: 	    push(@version_parts,$new_part);
1.259     banghart 3520: 	}
1.41      ng       3521:     }
1.301     albertel 3522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3524: 
1.344     albertel 3525:     if (%newrecord) {
                   3526:         if (@version_parts) {
1.364     banghart 3527:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3528:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3529: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3530: 	    foreach my $new_part (@version_parts) {
                   3531: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3532: 				$new_part,\%newrecord);
                   3533: 	    }
1.259     banghart 3534:         }
1.44      ng       3535: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3536: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3537: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.596.2.12.2.  8(raebur 3538:1): 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3539:     }
1.269     raeburn  3540:     if ($aggregateflag) {
                   3541:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3542: 			      $cdom,$cnum);
1.269     raeburn  3543:     }
1.596.2.12.2.  1(raebur 3544:5):     return ('',$pts,$wgt,$totchg);
                   3545:5): }
                   3546:5): 
                   3547:5): sub makehidden {
                   3548:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3549:5):     return unless (ref($record) eq 'HASH');
                   3550:5):     my %modified;
                   3551:5):     my $numchanged = 0;
                   3552:5):     if (exists($record->{$version.':keys'})) {
                   3553:5):         my $partsregexp = $parts;
                   3554:5):         $partsregexp =~ s/,/|/g;
                   3555:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3556:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3557:5):                  my $item = $1;
                   3558:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3559:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3560:5):                  }
                   3561:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3562:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3563:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3564:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3565:5):             }
                   3566:5):         }
                   3567:5):         if (keys(%modified)) {
                   3568:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3569:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3570:5):                 $numchanged ++;
                   3571:5):             }
                   3572:5):         }
                   3573:5):     }
                   3574:5):     return $numchanged;
1.36      ng       3575: }
1.322     albertel 3576: 
1.380     albertel 3577: sub check_and_remove_from_queue {
1.596.2.12.2.  8(raebur 3578:1):     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3579:     my @ungraded_parts;
                   3580:     foreach my $part (@{$parts}) {
                   3581: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3582: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3583: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3584: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3585: 		) {
1.596.2.12.2.  8(raebur 3586:1):             if ($queueable->{$part}) {
                   3587:1): 	        push(@ungraded_parts, $part);
                   3588:1):             }
1.380     albertel 3589: 	}
                   3590:     }
                   3591:     if ( !@ungraded_parts ) {
                   3592: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3593: 					       $cnum,$domain,$stuname);
                   3594:     }
                   3595: }
                   3596: 
1.337     banghart 3597: sub handback_files {
                   3598:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3599:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3600:     my $res_error;
                   3601:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3602:     if ($res_error) {
                   3603:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3604:         return;
                   3605:     }
1.596.2.4  raeburn  3606:     my @handedback;
                   3607:     my $file_msg;
1.375     albertel 3608:     my @part_response_id = &flatten_responseType($responseType);
                   3609:     foreach my $part_response_id (@part_response_id) {
                   3610:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3611: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3612:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3613:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3614:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3615: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3616:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3617:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3618:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3619:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3620: 		        &file_name_version_ext($answer_file);
1.355     banghart 3621: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3622:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3623:):                     my ($dir_list,$listerror) =
                   3624:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3625:):                                                  $domain,$stuname,$getpropath);
                   3626:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3627:3):                     # fix filename
1.355     banghart 3628:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3629:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3630:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3631:             	                                $save_file_name);
1.337     banghart 3632:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3633:                         $request->print('<br /><span class="LC_error">'.
                   3634:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3635:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3636:                                         '</span>');
1.356     banghart 3637:                     } else {
1.360     banghart 3638:                         # mark the file as read only
1.596.2.4  raeburn  3639:                         push(@handedback,$save_file_name);
1.367     albertel 3640: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3641: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3642: 			}
                   3643:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3644: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3645: 
1.337     banghart 3646:                     }
1.596.2.12.2.  3(raebur 3647:3):                     $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 3648:                 }
                   3649:             }
                   3650:         }
1.596.2.4  raeburn  3651:     }
                   3652:     if (@handedback > 0) {
                   3653:         $request->print('<br />');
                   3654:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3655:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3656:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3657:         my ($subject,$message);
                   3658:         if (scalar(@handedback) == 1) {
                   3659:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3660:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3661:         } else {
                   3662:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3663:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3664:         }
                   3665:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3666:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3667:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3668:         my ($feedurl,$showsymb) =
                   3669:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3670:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3671:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3672:         my $msgstatus =
                   3673:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3674:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3675:                  $restitle);
                   3676:         if ($msgstatus) {
                   3677:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3678:         }
                   3679:     }
1.338     banghart 3680:     return;
1.337     banghart 3681: }
                   3682: 
1.418     albertel 3683: sub get_feedurl_and_symb {
                   3684:     my ($symb,$uname,$udom) = @_;
                   3685:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3686:     $url = &Apache::lonnet::clutter($url);
                   3687:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3688: 					$symb,$udom,$uname);
                   3689:     if ($encrypturl =~ /^yes$/i) {
                   3690: 	&Apache::lonenc::encrypted(\$url,1);
                   3691: 	&Apache::lonenc::encrypted(\$symb,1);
                   3692:     }
                   3693:     return ($url,$symb);
                   3694: }
                   3695: 
1.313     banghart 3696: sub get_submitted_files {
                   3697:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3698:     my @files;
                   3699:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3700:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3701:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3702:     	    push(@files,$file_url.$file);
                   3703:         }
                   3704:     }
                   3705:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3706:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3707:     }
                   3708:     return (\@files);
                   3709: }
1.322     albertel 3710: 
1.269     raeburn  3711: # ----------- Provides number of tries since last reset.
                   3712: sub get_num_tries {
                   3713:     my ($record,$last_reset,$part) = @_;
                   3714:     my $timestamp = '';
                   3715:     my $num_tries = 0;
                   3716:     if ($$record{'version'}) {
                   3717:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3718:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3719:                 $timestamp = $$record{$version.':timestamp'};
                   3720:                 if ($timestamp > $last_reset) {
                   3721:                     $num_tries ++;
                   3722:                 } else {
                   3723:                     last;
                   3724:                 }
                   3725:             }
                   3726:         }
                   3727:     }
                   3728:     return $num_tries;
                   3729: }
                   3730: 
                   3731: # ----------- Determine decrements required in aggregate totals 
                   3732: sub decrement_aggs {
                   3733:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3734:     my %decrement = (
                   3735:                         attempts => 0,
                   3736:                         users => 0,
                   3737:                         correct => 0
                   3738:                     );
                   3739:     $decrement{'attempts'} = $aggtries;
                   3740:     if ($solvedstatus =~ /^correct/) {
                   3741:         $decrement{'correct'} = 1;
                   3742:     }
                   3743:     if ($aggtries == $totaltries) {
                   3744:         $decrement{'users'} = 1;
                   3745:     }
1.524     raeburn  3746:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3747:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3748:     }
                   3749:     return;
                   3750: }
                   3751: 
                   3752: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3753: sub get_last_resets {
1.270     albertel 3754:     my ($symb,$courseid,$partids) =@_;
                   3755:     my %last_resets;
1.269     raeburn  3756:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3757:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3758:     my @keys;
                   3759:     foreach my $part (@{$partids}) {
                   3760: 	push(@keys,"$symb\0$part\0resettime");
                   3761:     }
                   3762:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3763: 				     $cdom,$cname);
                   3764:     foreach my $part (@{$partids}) {
                   3765: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3766:     }
1.270     albertel 3767:     return %last_resets;
1.269     raeburn  3768: }
                   3769: 
1.251     banghart 3770: # ----------- Handles creating versions for portfolio files as answers
                   3771: sub version_portfiles {
1.343     banghart 3772:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3773:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3774:     my @returned_keys;
1.255     banghart 3775:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3776:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3777:     foreach my $key (keys(%$record)) {
1.259     banghart 3778:         my $new_portfiles;
1.263     banghart 3779:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3780:             my @versioned_portfiles;
1.367     albertel 3781:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3782:             foreach my $file (@portfiles) {
1.306     banghart 3783:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3784:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3785: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3786: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3787:):                 my $getpropath = 1;
                   3788:):                 my ($dir_list,$listerror) =
                   3789:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3790:):                                              $stu_name,$getpropath);
                   3791:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3792:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3793:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3794:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3795:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3796:                         [$directory.$new_answer],
1.306     banghart 3797:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3798:                 }
1.252     banghart 3799:             }
1.343     banghart 3800:             $$record{$key} = join(',',@versioned_portfiles);
                   3801:             push(@returned_keys,$key);
1.251     banghart 3802:         }
                   3803:     } 
1.343     banghart 3804:     return (@returned_keys);   
1.305     banghart 3805: }
                   3806: 
1.307     banghart 3807: sub get_next_version {
1.341     banghart 3808:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3809:     my $version;
1.596.2.12.2.  (raeburn 3810:):     if (ref($dir_list) eq 'ARRAY') {
                   3811:):         foreach my $row (@{$dir_list}) {
                   3812:):             my ($file) = split(/\&/,$row,2);
                   3813:):             my ($file_name,$file_version,$file_ext) =
                   3814:): 	        &file_name_version_ext($file);
                   3815:):             if (($file_name eq $answer_name) && 
                   3816:): 	        ($file_ext eq $answer_ext)) {
                   3817:):                 # gets here if filename and extension match, 
                   3818:):                 # regardless of version
1.307     banghart 3819:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3820:):                     # a versioned file is found  so save it for later
                   3821:):                     if ($file_version > $version) {
                   3822:): 		        $version = $file_version;
                   3823:):                     }
1.307     banghart 3824: 	        }
                   3825:             }
                   3826:         }
1.596.2.12.2.  (raeburn 3827:):     }
1.307     banghart 3828:     $version ++;
                   3829:     return($version);
                   3830: }
                   3831: 
1.305     banghart 3832: sub version_selected_portfile {
1.306     banghart 3833:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3834:     my ($answer_name,$answer_ver,$answer_ext) =
                   3835:         &file_name_version_ext($file_name);
                   3836:     my $new_answer;
                   3837:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3838:     if($env{'form.copy'} eq '-1') {
                   3839:         $new_answer = 'problem getting file';
                   3840:     } else {
                   3841:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3842:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3843:                             $stu_name,$domain,'copy',
                   3844: 		        '/portfolio'.$directory.$new_answer);
                   3845:     }    
                   3846:     return ($new_answer);
1.251     banghart 3847: }
                   3848: 
1.304     albertel 3849: sub file_name_version_ext {
                   3850:     my ($file)=@_;
                   3851:     my @file_parts = split(/\./, $file);
                   3852:     my ($name,$version,$ext);
                   3853:     if (@file_parts > 1) {
                   3854: 	$ext=pop(@file_parts);
                   3855: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3856: 	    $version=pop(@file_parts);
                   3857: 	}
                   3858: 	$name=join('.',@file_parts);
                   3859:     } else {
                   3860: 	$name=join('.',@file_parts);
                   3861:     }
                   3862:     return($name,$version,$ext);
                   3863: }
                   3864: 
1.44      ng       3865: #--------------------------------------------------------------------------------------
                   3866: #
                   3867: #-------------------------- Next few routines handles grading by section or whole class
                   3868: #
                   3869: #--- Javascript to handle grading by section or whole class
1.42      ng       3870: sub viewgrades_js {
                   3871:     my ($request) = shift;
                   3872: 
1.539     riegler  3873:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3874:6):     &js_escape(\$alertmsg);
          1(raebur 3875:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3876:    function writePoint(partid,weight,point) {
1.125     ng       3877: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3878: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3879: 	if (point == "textval") {
1.125     ng       3880: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3881: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3882: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3883: 		var resetbox = false;
                   3884: 		for (var i=0; i<radioButton.length; i++) {
                   3885: 		    if (radioButton[i].checked) {
                   3886: 			textbox.value = i;
                   3887: 			resetbox = true;
                   3888: 		    }
                   3889: 		}
                   3890: 		if (!resetbox) {
                   3891: 		    textbox.value = "";
                   3892: 		}
                   3893: 		return;
                   3894: 	    }
1.109     matthew  3895: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3896: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3897: 				   ") greater than the weight for the part. Accept?");
                   3898: 		if (resp == false) {
                   3899: 		    textbox.value = "";
                   3900: 		    return;
                   3901: 		}
                   3902: 	    }
1.42      ng       3903: 	    for (var i=0; i<radioButton.length; i++) {
                   3904: 		radioButton[i].checked=false;
1.109     matthew  3905: 		if (parseFloat(point) == i) {
1.42      ng       3906: 		    radioButton[i].checked=true;
                   3907: 		}
                   3908: 	    }
1.41      ng       3909: 
1.42      ng       3910: 	} else {
1.125     ng       3911: 	    textbox.value = parseFloat(point);
1.42      ng       3912: 	}
1.41      ng       3913: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3914: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3915: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3916: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3917: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3918: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3919: 	    if (saveval != "correct") {
                   3920: 		scorename.value = point;
1.43      ng       3921: 		if (selname[0].selected != true) {
                   3922: 		    selname[0].selected = true;
                   3923: 		}
1.42      ng       3924: 	    }
                   3925: 	}
1.125     ng       3926: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3927:     }
                   3928: 
                   3929:     function writeRadText(partid,weight) {
1.125     ng       3930: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3931: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3932:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3933: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3934: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3935: 	    for (var i=0; i<radioButton.length; i++) {
                   3936: 		radioButton[i].checked=false;
                   3937: 
                   3938: 	    }
                   3939: 	    textbox.value = "";
                   3940: 
                   3941: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3942: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3943: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3944: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3945: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3946: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3947: 		if ((saveval != "correct") || override) {
1.42      ng       3948: 		    scorename.value = "";
1.125     ng       3949: 		    if (selval[1].selected) {
                   3950: 			selname[1].selected = true;
                   3951: 		    } else {
                   3952: 			selname[2].selected = true;
                   3953: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3954: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3955: 		    }
1.42      ng       3956: 		}
                   3957: 	    }
1.43      ng       3958: 	} else {
                   3959: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3960: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3961: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3962: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3963: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3964: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3965: 		if ((saveval != "correct") || override) {
1.125     ng       3966: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3967: 		    selname[0].selected = true;
                   3968: 		}
                   3969: 	    }
                   3970: 	}	    
1.42      ng       3971:     }
                   3972: 
                   3973:     function changeSelect(partid,user) {
1.125     ng       3974: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3975: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3976: 	var point  = textbox.value;
1.125     ng       3977: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3978: 
1.109     matthew  3979: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3980: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3981: 	    textbox.value = "";
                   3982: 	    return;
                   3983: 	}
1.109     matthew  3984: 	if (parseFloat(point) > parseFloat(weight)) {
                   3985: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3986: 			       ") greater than the weight of the part. Accept?");
                   3987: 	    if (resp == false) {
                   3988: 		textbox.value = "";
                   3989: 		return;
                   3990: 	    }
                   3991: 	}
1.42      ng       3992: 	selval[0].selected = true;
                   3993:     }
                   3994: 
                   3995:     function changeOneScore(partid,user) {
1.125     ng       3996: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3997: 	if (selval[1].selected || selval[2].selected) {
                   3998: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3999: 	    if (selval[2].selected) {
                   4000: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   4001: 	    }
1.269     raeburn  4002:         }
1.42      ng       4003:     }
                   4004: 
                   4005:     function resetEntry(numpart) {
                   4006: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       4007: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   4008: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   4009: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   4010: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       4011: 	    for (var i=0; i<radioButton.length; i++) {
                   4012: 		radioButton[i].checked=false;
                   4013: 
                   4014: 	    }
                   4015: 	    textbox.value = "";
                   4016: 	    selval[0].selected = true;
                   4017: 
                   4018: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       4019: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 4020: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       4021: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   4022: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   4023: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   4024: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   4025: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   4026: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       4027: 		if (saveselval == "excused") {
1.43      ng       4028: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       4029: 		} else {
1.43      ng       4030: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       4031: 		}
                   4032: 	    }
1.41      ng       4033: 	}
1.42      ng       4034:     }
                   4035: 
1.41      ng       4036: VIEWJAVASCRIPT
1.42      ng       4037: }
                   4038: 
1.44      ng       4039: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4040: sub viewgrades {
1.596.2.12.2.  1(raebur 4041:0):     my ($request,$symb) = @_;
1.42      ng       4042:     &viewgrades_js($request);
1.41      ng       4043: 
1.168     albertel 4044:     #need to make sure we have the correct data for later EXT calls, 
                   4045:     #thus invalidate the cache
                   4046:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4047:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4048:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4049:     &Apache::lonnet::clear_EXT_cache_status();
                   4050: 
1.398     albertel 4051:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4052: 
                   4053:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4054:     $result.=&jscriptNform($symb);
1.41      ng       4055: 
1.44      ng       4056:     #beginning of class grading form
1.442     banghart 4057:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4058:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4059: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4060: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4061: 	&build_section_inputs().
1.442     banghart 4062: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4063: 
1.596.2.12.2.  7(raebur 4064:6):     #retrieve selected groups
                   4065:6):     my (@groups,$group_display);
          8(raebur 4066:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4067:6):     if (grep(/^all$/,@groups)) {
                   4068:6):         @groups = ('all');
                   4069:6):     } elsif (grep(/^none$/,@groups)) {
                   4070:6):         @groups = ('none');
                   4071:6):     } elsif (@groups > 0) {
                   4072:6):         $group_display = join(', ',@groups);
                   4073:6):     }
                   4074:6): 
                   4075:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4076:1):     if ($env{'request.course.sec'} ne '') {
                   4077:1):         @sections = ($env{'request.course.sec'});
                   4078:1):     } else {
                   4079:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4080:1):     }
                   4081:1): 
                   4082:1): # Check if Save button should be usable
                   4083:1):     my $disabled = ' disabled="disabled"';
                   4084:1):     if ($perm{'mgr'}) {
                   4085:1):         if (grep(/^all$/,@sections)) {
                   4086:1):             undef($disabled);
                   4087:1):         } else {
                   4088:1):             foreach my $sec (@sections) {
                   4089:1):                 if (&canmodify($sec)) {
                   4090:1):                     undef($disabled);
                   4091:1):                     last;
                   4092:1):                 }
                   4093:1):             }
                   4094:1):         }
                   4095:1):     }
          7(raebur 4096:6):     if (grep(/^all$/,@sections)) {
                   4097:6):         @sections = ('all');
                   4098:6):         if ($group_display) {
                   4099:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4100:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4101:6):         } elsif (grep(/^none$/,@groups)) {
                   4102:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4103:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4104:6):         } else {
                   4105:6):             $common_header = &mt('Assign Common Grade to Class');
                   4106:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4107:6):         }
                   4108:6):     } elsif (grep(/^none$/,@sections)) {
                   4109:6):         @sections = ('none');
                   4110:6):         if ($group_display) {
                   4111:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4112:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4113:6):         } elsif (grep(/^none$/,@groups)) {
                   4114:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4115:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4116:6):         } else {
                   4117:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4118:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4119:6):         }
                   4120:6):     } else {
                   4121:6):         $section_display = join (", ",@sections);
                   4122:6):         if ($group_display) {
                   4123:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4124:6):                                  $section_display,$group_display);
                   4125:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4126:6):                                    $section_display,$group_display);
                   4127:6):         } elsif (grep(/^none$/,@groups)) {
                   4128:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4129:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4130:6):         } else {
                   4131:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4132:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4133:6):         }
1.52      albertel 4134:     }
1.596.2.12.2.  7(raebur 4135:6):     my %submit_types = &substatus_options();
                   4136:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4137:6): 
                   4138:6):     if ($env{'form.submitonly'} eq 'all') {
                   4139:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4140:6):     } else {
                   4141:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   4142:6):     }
                   4143:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4144:     #radio buttons/text box for assigning points for a section or class.
                   4145:     #handles different parts of a problem
1.582     raeburn  4146:     my $res_error;
                   4147:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4148:     if ($res_error) {
                   4149:         return &navmap_errormsg();
                   4150:     }
1.42      ng       4151:     my %weight = ();
                   4152:     my $ctsparts = 0;
1.45      ng       4153:     my %seen = ();
1.375     albertel 4154:     my @part_response_id = &flatten_responseType($responseType);
                   4155:     foreach my $part_response_id (@part_response_id) {
                   4156:     	my ($partid,$respid) = @{ $part_response_id };
                   4157: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4158: 	next if $seen{$partid};
                   4159: 	$seen{$partid}++;
1.42      ng       4160: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4161: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4162: 
1.324     albertel 4163: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4164: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4165: 	my $ctr = 0;
1.42      ng       4166: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4167: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4168: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4169: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4170: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4171: 	    $ctr++;
                   4172: 	}
1.485     albertel 4173: 	$radio.='</tr></table>';
                   4174: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4175: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4176: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4177: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4178:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4179:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4180:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4181: 		$weight{$partid}.')"> '.
1.401     albertel 4182: 	    '<option selected="selected"> </option>'.
1.485     albertel 4183: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4184: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4185: 	    '</select></td>'.
                   4186:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4187: 	$line.='<input type="hidden" name="partid_'.
                   4188: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4189: 	$line.='<input type="hidden" name="weight_'.
                   4190: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4191: 
                   4192: 	$result.=
                   4193: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4194: 	    '<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 4195: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4196: 	$ctsparts++;
1.41      ng       4197:     }
1.474     albertel 4198:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4199: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4200:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4201: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4202: 
1.44      ng       4203:     #table listing all the students in a section/class
                   4204:     #header of table
1.596.2.12.2.  7(raebur 4205:6):     if ($env{'form.submitonly'} eq 'all') { 
                   4206:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4207:6):     } else {
                   4208:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   4209:6):     }
                   4210:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4211: 	      &Apache::loncommon::start_data_table_header_row().
                   4212: 	      '<th>'.&mt('No.').'</th>'.
                   4213: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4214:     my $partserror;
                   4215:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4216:     if ($partserror) {
                   4217:         return &navmap_errormsg();
                   4218:     }
1.324     albertel 4219:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4220:     my @partids = ();
1.41      ng       4221:     foreach my $part (@parts) {
                   4222: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  4223:         my $narrowtext = &mt('Tries');
                   4224: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       4225: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 4226: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4227:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4228:0): #
                   4229:0): # FIXME: Looks like $display looks at English text
                   4230:0): #
1.324     albertel 4231: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4232: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4233: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4234:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4235:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4236: 	    next;
1.485     albertel 4237: 	    
1.207     albertel 4238: 	} else {
1.485     albertel 4239: 	    if ($display =~ /Problem Status/) {
                   4240: 		my $grade_status_mt = &mt('Grade Status');
                   4241: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4242: 	    }
                   4243: 	    my $part_mt = &mt('Part:');
                   4244: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4245: 	}
1.485     albertel 4246: 
1.474     albertel 4247: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4248:     }
1.474     albertel 4249:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4250: 
1.270     albertel 4251:     my %last_resets = 
                   4252: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4253: 
1.41      ng       4254:     #get info for each student
1.44      ng       4255:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4256:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4257:     my $ctr = 0;
1.294     albertel 4258:     foreach (sort 
                   4259: 	     {
                   4260: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4261: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4262: 		 }
                   4263: 		 return $a cmp $b;
                   4264: 	     } (keys(%$fullname))) {
1.324     albertel 4265: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 4266:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       4267:     }
1.474     albertel 4268:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4269:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4270:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4271: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4272:6):     if ($ctr == 0) {
1.442     banghart 4273:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4274:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4275:6):                 '<span class="LC_warning">';
                   4276:6):         if ($env{'form.submitonly'} eq 'all') {
                   4277:6):             if (grep(/^all$/,@sections)) {
                   4278:6):                 if (grep(/^all$/,@groups)) {
                   4279:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4280:6):                                    $stu_status);
                   4281:6):                 } elsif (grep(/^none$/,@groups)) {
                   4282:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4283:6):                                    $stu_status);
                   4284:6):                 } else {
                   4285:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4286:6):                                    $group_display,$stu_status);
                   4287:6):                 }
                   4288:6):             } elsif (grep(/^none$/,@sections)) {
                   4289:6):                 if (grep(/^all$/,@groups)) {
                   4290:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4291:6):                                    $stu_status);
                   4292:6):                 } elsif (grep(/^none$/,@groups)) {
                   4293:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4294:6):                                    $stu_status);
                   4295:6):                 } else {
                   4296:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4297:6):                                    $group_display,$stu_status);
                   4298:6):                 }
                   4299:6):             } else {
                   4300:6):                 if (grep(/^all$/,@groups)) {
                   4301:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4302:6):                                    $section_display,$stu_status);
                   4303:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4304:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4305:6):                                    $section_display,$stu_status);
                   4306:6):                 } else {
                   4307:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4308:6):                                    $section_display,$group_display,$stu_status);
                   4309:6):                 }
                   4310:6):             }
                   4311:6):         } else {
                   4312:6):             if (grep(/^all$/,@sections)) {
                   4313:6):                 if (grep(/^all$/,@groups)) {
                   4314:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4315:6):                                    $stu_status,$submission_status);
                   4316:6):                 } elsif (grep(/^none$/,@groups)) {
                   4317:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4318:6):                                    $stu_status,$submission_status);
                   4319:6):                 } else {
                   4320:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4321:6):                                    $group_display,$stu_status,$submission_status);
                   4322:6):                 }
                   4323:6):             } elsif (grep(/^none$/,@sections)) {
                   4324:6):                 if (grep(/^all$/,@groups)) {
                   4325:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4326:6):                                    $stu_status,$submission_status);
                   4327:6):                 } elsif (grep(/^none$/,@groups)) {
                   4328:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4329:6):                                    $stu_status,$submission_status);
                   4330:6):                 } else {
                   4331:6):                     $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.',
                   4332:6):                                    $group_display,$stu_status,$submission_status);
                   4333:6):                 }
                   4334:6):             } else {
                   4335:6):                 if (grep(/^all$/,@groups)) {
                   4336:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4337:6):                                    $section_display,$stu_status,$submission_status);
                   4338:6):                 } elsif (grep(/^none$/,@groups)) {
                   4339:6):                     $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.',
                   4340:6):                                    $section_display,$stu_status,$submission_status);
                   4341:6):                 } else {
                   4342:6):                     $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.',
                   4343:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4344:6):                 }
                   4345:6):             }
                   4346:6): 	}
                   4347:6): 	$result .= '</span><br />';
1.96      albertel 4348:     }
1.41      ng       4349:     return $result;
                   4350: }
                   4351: 
1.596.2.12.2.  7(raebur 4352:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4353: sub viewstudentgrade {
1.324     albertel 4354:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4355:     my ($uname,$udom) = split(/:/,$student);
                   4356:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4357:6):     my $submitonly = $env{'form.submitonly'};
                   4358:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4359:6):         my %partstatus = ();
                   4360:6):         if (ref($parts) eq 'ARRAY') {
                   4361:6):             foreach my $apart (@{$parts}) {
                   4362:6):                 my ($part,$type) = &split_part_type($apart);
                   4363:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4364:6):                 $status = 'nothing' if ($status eq '');
                   4365:6):                 $partstatus{$part}      = $status;
                   4366:6):                 my $subkey = "resource.$part.submitted_by";
                   4367:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4368:6):             }
                   4369:6):             my $submitted = 0;
                   4370:6):             my $graded = 0;
                   4371:6):             my $incorrect = 0;
                   4372:6):             foreach my $key (keys(%partstatus)) {
                   4373:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4374:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4375:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4376:6): 
                   4377:6):                 my $partid = (split(/\./,$key))[1];
                   4378:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4379:6):                     $submitted = 0;
                   4380:6):                 }
                   4381:6):             }
                   4382:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4383:6):                                        $submitonly eq 'incorrect' ||
                   4384:6):                                        $submitonly eq 'graded'));
                   4385:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4386:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4387:6):         }
                   4388:6):     }
                   4389:6):     if ($submitonly eq 'queued') {
                   4390:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4391:6):         my %queue_status =
                   4392:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4393:6):                                                     $udom,$uname);
                   4394:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4395:6):     }
                   4396:6):     $$ctr++;
                   4397:6):     my %aggregates = ();
1.474     albertel 4398:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4399:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4400:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4401: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4402: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4403: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4404:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4405:     foreach my $apart (@$parts) {
                   4406: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4407: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4408:         $result.='<td align="center">';
1.269     raeburn  4409:         my ($aggtries,$totaltries);
                   4410:         unless (exists($aggregates{$part})) {
1.270     albertel 4411: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4412: 
                   4413: 	    $aggtries = $totaltries;
1.269     raeburn  4414:             if ($$last_resets{$part}) {  
1.270     albertel 4415:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4416: 					   $part);
                   4417:             }
1.269     raeburn  4418:             $result.='<input type="hidden" name="'.
                   4419:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4420:             $result.='<input type="hidden" name="'.
                   4421:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4422:             $aggregates{$part} = 1;
                   4423:         }
1.41      ng       4424: 	if ($type eq 'awarded') {
1.320     albertel 4425: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4426: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4427: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4428: 	    $result.='<input type="text" name="'.
1.89      albertel 4429: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4430:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4431: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4432: 	} elsif ($type eq 'solved') {
                   4433: 	    my ($status,$foo)=split(/_/,$score,2);
                   4434: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4435: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4436: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4437: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4438: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4439:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4440: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4441: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4442: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4443: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4444: 	} else {
                   4445: 	    $result.='<input type="hidden" name="'.
                   4446: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4447: 		    "\n";
1.233     albertel 4448: 	    $result.='<input type="text" name="'.
1.122     ng       4449: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4450: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4451: 	}
                   4452:     }
1.474     albertel 4453:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4454:     return $result;
1.38      ng       4455: }
                   4456: 
1.44      ng       4457: #--- change scores for all the students in a section/class
                   4458: #    record does not get update if unchanged
1.38      ng       4459: sub editgrades {
1.596.2.12.2.  1(raebur 4460:0):     my ($request,$symb) = @_;
1.41      ng       4461: 
1.433     banghart 4462:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4463:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4464:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4465: 
1.477     albertel 4466:     my $result= &Apache::loncommon::start_data_table().
                   4467: 	&Apache::loncommon::start_data_table_header_row().
                   4468: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4469: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4470:     my %scoreptr = (
                   4471: 		    'correct'  =>'correct_by_override',
                   4472: 		    'incorrect'=>'incorrect_by_override',
                   4473: 		    'excused'  =>'excused',
                   4474: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4475:                     'credited' =>'credit_attempted',
1.43      ng       4476: 		    'nothing'  => '',
                   4477: 		    );
1.257     albertel 4478:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4479: 
1.44      ng       4480:     my (@partid);
                   4481:     my %weight = ();
1.54      albertel 4482:     my %columns = ();
1.44      ng       4483:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4484: 
1.582     raeburn  4485:     my $partserror;
                   4486:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4487:     if ($partserror) {
                   4488:         return &navmap_errormsg();
                   4489:     }
1.54      albertel 4490:     my $header;
1.257     albertel 4491:     while ($ctr < $env{'form.totalparts'}) {
                   4492: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4493: 	push(@partid,$partid);
1.257     albertel 4494: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4495: 	$ctr++;
1.54      albertel 4496:     }
1.324     albertel 4497:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4498:8):     my $totcolspan = 0;
1.54      albertel 4499:     foreach my $partid (@partid) {
1.478     albertel 4500: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4501: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4502: 	$columns{$partid}=2;
                   4503: 	foreach my $stores (@parts) {
                   4504: 	    my ($part,$type) = &split_part_type($stores);
                   4505: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4506: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4507: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4508: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4509:             my $narrowtext = &mt('Tries');
                   4510: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4511: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4512: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4513: 	    $columns{$partid}+=2;
                   4514: 	}
1.596.2.12.2.  2(raebur 4515:8):         $totcolspan += $columns{$partid};
1.54      albertel 4516:     }
                   4517:     foreach my $partid (@partid) {
1.324     albertel 4518: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4519: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4520: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4521: 	    '</th>';
1.54      albertel 4522: 
1.44      ng       4523:     }
1.477     albertel 4524:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4525: 	&Apache::loncommon::start_data_table_header_row().
                   4526: 	$header.
                   4527: 	&Apache::loncommon::end_data_table_header_row();
                   4528:     my @noupdate;
1.126     ng       4529:     my ($updateCtr,$noupdateCtr) = (1,1);
1.596.2.12.2.  8(raebur 4530:1):     my ($got_types,%queueable);
1.257     albertel 4531:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4532: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4533: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4534: 	my %newrecord;
                   4535: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4536:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4537:8):         my $canmodify = &canmodify($usec);
                   4538:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4539:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4540:8):         if (!$canmodify) {
                   4541:8):             push(@noupdate,
                   4542:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4543:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4544:8):             next;
                   4545:8):         }
1.269     raeburn  4546:         my %aggregate = ();
                   4547:         my $aggregateflag = 0;
1.281     albertel 4548: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4549: 	foreach (@partid) {
1.257     albertel 4550: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4551: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4552: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4553: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4554: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4555: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4556: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4557: 	    my $score;
                   4558: 	    if ($partial eq '') {
1.257     albertel 4559: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4560: 	    } elsif ($partial > 0) {
                   4561: 		$score = 'correct_by_override';
                   4562: 	    } elsif ($partial == 0) {
                   4563: 		$score = 'incorrect_by_override';
                   4564: 	    }
1.257     albertel 4565: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4566: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4567: 
1.292     albertel 4568: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4569: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4570: 	    if ($dropMenu eq 'reset status' &&
                   4571: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4572: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4573: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4574: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4575: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4576: 		$updateflag = 1;
1.269     raeburn  4577:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4578:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4579:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4580:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4581:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4582:                     $aggregateflag = 1;
                   4583:                 }
1.139     albertel 4584: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4585: 		$updateflag = 1;
                   4586: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4587: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4588: 		$rec_update++;
1.125     ng       4589: 	    }
                   4590: 
1.93      albertel 4591: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4592: 		'<td align="center">'.$awarded.
                   4593: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4594: 
1.54      albertel 4595: 
                   4596: 	    my $partid=$_;
                   4597: 	    foreach my $stores (@parts) {
                   4598: 		my ($part,$type) = &split_part_type($stores);
                   4599: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4600: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4601: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4602: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4603: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4604: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4605: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4606: 		    $updateflag=1;
                   4607: 		}
1.93      albertel 4608: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4609: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4610: 	    }
1.44      ng       4611: 	}
1.477     albertel 4612: 	$line.="\n";
1.301     albertel 4613: 
                   4614: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4615: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4616: 
1.44      ng       4617: 	if ($updateflag) {
                   4618: 	    $count++;
1.257     albertel 4619: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4620: 				    $udom,$uname);
1.301     albertel 4621: 
                   4622: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4623: 					      $cnum,$udom,$uname)) {
                   4624: 		# need to figure out if should be in queue.
                   4625: 		my %record =  
                   4626: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4627: 					     $udom,$uname);
                   4628: 		my $all_graded = 1;
                   4629: 		my $none_graded = 1;
1.596.2.12.2.  8(raebur 4630:1):                 unless ($got_types) {
                   4631:1):                     my $error;
                   4632:1):                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4633:1):                     unless ($error) {
                   4634:1):                         foreach my $part (@parts) {
                   4635:1):                             if (ref($resptype->{$part}) eq 'HASH') {
                   4636:1):                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4637:1):                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4638:1):                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4639:1):                                         $queueable{$part} = 1;
                   4640:1):                                         last;
                   4641:1):                                     }
                   4642:1):                                 }
                   4643:1):                             }
                   4644:1):                         }
                   4645:1):                     }
                   4646:1):                     $got_types = 1;
                   4647:1):                 }
1.301     albertel 4648: 		foreach my $part (@parts) {
1.596.2.12.2.  8(raebur 4649:1):                     if ($queueable{$part}) {
                   4650:1): 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4651:1): 			    $all_graded = 0;
                   4652:1): 		        } else {
                   4653:1): 			    $none_graded = 0;
                   4654:1): 		        }
                   4655:1):                     }
1.301     albertel 4656: 		}
                   4657: 
                   4658: 		if ($all_graded || $none_graded) {
                   4659: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4660: 							   $symb,$cdom,$cnum,
                   4661: 							   $udom,$uname);
                   4662: 		}
                   4663: 	    }
                   4664: 
1.477     albertel 4665: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4666: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4667: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4668: 	    $updateCtr++;
1.93      albertel 4669: 	} else {
1.477     albertel 4670: 	    push(@noupdate,
                   4671: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4672: 	    $noupdateCtr++;
1.44      ng       4673: 	}
1.269     raeburn  4674:         if ($aggregateflag) {
                   4675:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4676: 				  $cdom,$cnum);
1.269     raeburn  4677:         }
1.93      albertel 4678:     }
1.477     albertel 4679:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4680:8):         my $numcols=$totcolspan+2;
1.477     albertel 4681: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4682: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4683: 	    &mt('No Changes Occurred For the Students Below').
                   4684: 	    '</td>'.
1.477     albertel 4685: 	    &Apache::loncommon::end_data_table_row();
                   4686: 	foreach my $line (@noupdate) {
                   4687: 	    $result.=
                   4688: 		&Apache::loncommon::start_data_table_row().
                   4689: 		$line.
                   4690: 		&Apache::loncommon::end_data_table_row();
                   4691: 	}
1.44      ng       4692:     }
1.596.2.12.2.  1(raebur 4693:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4694:     my $msg = '<p><b>'.
                   4695: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4696: 	    $rec_update,$count).'</b><br />'.
                   4697: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4698: 	'</b></p>';
1.44      ng       4699:     return $title.$msg.$result;
1.5       albertel 4700: }
1.54      albertel 4701: 
                   4702: sub split_part_type {
                   4703:     my ($partstr) = @_;
                   4704:     my ($temp,@allparts)=split(/_/,$partstr);
                   4705:     my $type=pop(@allparts);
1.439     albertel 4706:     my $part=join('_',@allparts);
1.54      albertel 4707:     return ($part,$type);
                   4708: }
                   4709: 
1.44      ng       4710: #------------- end of section for handling grading by section/class ---------
                   4711: #
                   4712: #----------------------------------------------------------------------------
                   4713: 
1.5       albertel 4714: 
1.44      ng       4715: #----------------------------------------------------------------------------
                   4716: #
                   4717: #-------------------------- Next few routines handles grading by csv upload
                   4718: #
                   4719: #--- Javascript to handle csv upload
1.27      albertel 4720: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4721:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4722:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4723:6):   &js_escape(\$error1);
                   4724:6):   &js_escape(\$error2);
1.27      albertel 4725:   return(<<ENDPICK);
                   4726:   function verify(vf) {
                   4727:     var foundsomething=0;
                   4728:     var founduname=0;
1.243     albertel 4729:     var foundID=0;
1.27      albertel 4730:     for (i=0;i<=vf.nfields.value;i++) {
                   4731:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4732:       if (i==0 && tw!=0) { foundID=1; }
                   4733:       if (i==1 && tw!=0) { founduname=1; }
                   4734:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4735:     }
1.246     albertel 4736:     if (founduname==0 && foundID==0) {
                   4737: 	alert('$error1');
                   4738: 	return;
1.27      albertel 4739:     }
                   4740:     if (foundsomething==0) {
1.246     albertel 4741: 	alert('$error2');
                   4742: 	return;
1.27      albertel 4743:     }
                   4744:     vf.submit();
                   4745:   }
                   4746:   function flip(vf,tf) {
                   4747:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4748:     var i;
                   4749:     for (i=0;i<=vf.nfields.value;i++) {
                   4750:       //can not pick the same destination field for both name and domain
                   4751:       if (((i ==0)||(i ==1)) && 
                   4752:           ((tf==0)||(tf==1)) && 
                   4753:           (i!=tf) &&
                   4754:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4755:         eval('vf.f'+i+'.selectedIndex=0;')
                   4756:       }
                   4757:     }
                   4758:   }
                   4759: ENDPICK
                   4760: }
                   4761: 
                   4762: sub csvupload_javascript_forward_associate {
1.573     bisitz   4763:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4764:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4765:6):   &js_escape(\$error1);
                   4766:6):   &js_escape(\$error2);
1.27      albertel 4767:   return(<<ENDPICK);
                   4768:   function verify(vf) {
                   4769:     var foundsomething=0;
                   4770:     var founduname=0;
1.243     albertel 4771:     var foundID=0;
1.27      albertel 4772:     for (i=0;i<=vf.nfields.value;i++) {
                   4773:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4774:       if (tw==1) { foundID=1; }
                   4775:       if (tw==2) { founduname=1; }
                   4776:       if (tw>3) { foundsomething=1; }
1.27      albertel 4777:     }
1.246     albertel 4778:     if (founduname==0 && foundID==0) {
                   4779: 	alert('$error1');
                   4780: 	return;
1.27      albertel 4781:     }
                   4782:     if (foundsomething==0) {
1.246     albertel 4783: 	alert('$error2');
                   4784: 	return;
1.27      albertel 4785:     }
                   4786:     vf.submit();
                   4787:   }
                   4788:   function flip(vf,tf) {
                   4789:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4790:     var i;
                   4791:     //can not pick the same destination field twice
                   4792:     for (i=0;i<=vf.nfields.value;i++) {
                   4793:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4794:         eval('vf.f'+i+'.selectedIndex=0;')
                   4795:       }
                   4796:     }
                   4797:   }
                   4798: ENDPICK
                   4799: }
                   4800: 
1.26      albertel 4801: sub csvuploadmap_header {
1.324     albertel 4802:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4803:     my $javascript;
1.257     albertel 4804:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4805: 	$javascript=&csvupload_javascript_reverse_associate();
                   4806:     } else {
                   4807: 	$javascript=&csvupload_javascript_forward_associate();
                   4808:     }
1.45      ng       4809: 
1.257     albertel 4810:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4811:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4812:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4813:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4814:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4815:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4816:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4817:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4818:0): <br />
                   4819:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4820: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4821: <input type="hidden" name="associate"  value="" />
                   4822: <input type="hidden" name="phase"      value="three" />
                   4823: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4824: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4825: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4826: <input type="hidden" name="upfile_associate" 
1.257     albertel 4827:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4828: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4829: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4830: <hr />
                   4831: ENDPICK
1.596.2.12.2.  1(raebur 4832:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4833:     return '';
1.26      albertel 4834: 
                   4835: }
                   4836: 
                   4837: sub csvupload_fields {
1.582     raeburn  4838:     my ($symb,$errorref) = @_;
                   4839:     my (@parts) = &getpartlist($symb,$errorref);
                   4840:     if (ref($errorref)) {
                   4841:         if ($$errorref) {
                   4842:             return;
                   4843:         }
                   4844:     }
                   4845: 
1.556     weissno  4846:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4847: 		['username','Student Username'],
                   4848: 		['domain','Student Domain']);
1.324     albertel 4849:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4850:     foreach my $part (sort(@parts)) {
                   4851: 	my @datum;
                   4852: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4853: 	my $name=$part;
                   4854: 	if  (!$display) { $display = $name; }
                   4855: 	@datum=($name,$display);
1.244     albertel 4856: 	if ($name=~/^stores_(.*)_awarded/) {
                   4857: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4858: 	}
1.41      ng       4859: 	push(@fields,\@datum);
                   4860:     }
                   4861:     return (@fields);
1.26      albertel 4862: }
                   4863: 
                   4864: sub csvuploadmap_footer {
1.41      ng       4865:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4866:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4867:     $request->print(<<ENDPICK);
1.26      albertel 4868: </table>
                   4869: <input type="hidden" name="nfields" value="$i" />
                   4870: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4871:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4872: </form>
                   4873: ENDPICK
                   4874: }
                   4875: 
1.283     albertel 4876: sub checkforfile_js {
1.539     riegler  4877:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4878:6):     &js_escape(\$alertmsg);
          1(raebur 4879:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4880:     function checkUpload(formname) {
                   4881: 	if (formname.upfile.value == "") {
1.539     riegler  4882: 	    alert("$alertmsg");
1.86      ng       4883: 	    return false;
                   4884: 	}
                   4885: 	formname.submit();
                   4886:     }
                   4887: CSVFORMJS
1.283     albertel 4888:     return $result;
                   4889: }
                   4890: 
                   4891: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4892:0):     my ($request,$symb) = @_;
1.283     albertel 4893:     if (!$symb) {return '';}
                   4894:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4895:0):     $result.=&Apache::loncommon::start_data_table().
                   4896:0):              &Apache::loncommon::start_data_table_header_row().
                   4897:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4898:0):              &Apache::loncommon::end_data_table_header_row().
                   4899:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4900:     my $upload=&mt("Upload Scores");
1.86      ng       4901:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4902:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4903:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4904:     $result.=<<ENDUPFORM;
1.106     albertel 4905: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4906: <input type="hidden" name="symb" value="$symb" />
                   4907: <input type="hidden" name="command" value="csvuploadmap" />
                   4908: $upfile_select
1.589     bisitz   4909: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4910: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4911: </form>
                   4912: ENDUPFORM
1.370     www      4913:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4914:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4915:0):             '</td>'.
                   4916:0):             &Apache::loncommon::end_data_table_row().
                   4917:0):             &Apache::loncommon::end_data_table();
1.86      ng       4918:     return $result;
                   4919: }
                   4920: 
                   4921: 
1.26      albertel 4922: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4923:0):     my ($request,$symb) = @_;
1.41      ng       4924:     if (!$symb) {return '';}
1.72      ng       4925: 
1.41      ng       4926:     my $datatoken;
1.257     albertel 4927:     if (!$env{'form.datatoken'}) {
1.41      ng       4928: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4929:     } else {
1.596.2.12.2.  3(raebur 4930:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4931:8):         if ($datatoken ne '') { 
                   4932:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4933:8):         }
1.26      albertel 4934:     }
1.41      ng       4935:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4936:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4937:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4938:     my ($i,$keyfields);
                   4939:     if (@records) {
1.582     raeburn  4940:         my $fieldserror;
                   4941: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4942:         if ($fieldserror) {
                   4943:             $request->print(&navmap_errormsg());
                   4944:             return;
                   4945:         }
1.257     albertel 4946: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4947: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4948: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4949: 							  \@fields);
                   4950: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4951: 	    chop($keyfields);
                   4952: 	} else {
                   4953: 	    unshift(@fields,['none','']);
                   4954: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4955: 							    \@fields);
1.311     banghart 4956:             foreach my $rec (@records) {
                   4957:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4958:                 if (%temp) {
                   4959:                     $keyfields=join(',',sort(keys(%temp)));
                   4960:                     last;
                   4961:                 }
                   4962:             }
1.41      ng       4963: 	}
                   4964:     }
                   4965:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4966: 
1.41      ng       4967:     return '';
1.27      albertel 4968: }
                   4969: 
1.246     albertel 4970: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 4971:0):     my ($request,$symb)= @_;
                   4972:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 4973:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4974:     my $ignore=&mt('Ignore First Line');
                   4975:     $request->print(<<ENDPICK);
                   4976: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4977: <input type="hidden" name="command"    value="csvuploadassign" />
                   4978: <p>
                   4979: <label>
                   4980:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 4981:0):    $overwrite
1.246     albertel 4982: </label>
                   4983: </p>
                   4984: ENDPICK
                   4985:     my %fields=&get_fields();
                   4986:     if (!defined($fields{'domain'})) {
1.257     albertel 4987: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 4988:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4989:     }
1.257     albertel 4990:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4991: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4992: 	my $cleankey=$1;
                   4993: 	if ($cleankey eq 'command') { next; }
                   4994: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4995: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4996:     }
                   4997:     # FIXME do a check for any duplicated user ids...
                   4998:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4999:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 5000: <hr /></form>'."\n");
1.246     albertel 5001:     return '';
                   5002: }
                   5003: 
                   5004: sub get_fields {
                   5005:     my %fields;
1.257     albertel 5006:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   5007:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   5008: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   5009: 	    if ($env{'form.f'.$i} ne 'none') {
                   5010: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       5011: 	    }
                   5012: 	} else {
1.257     albertel 5013: 	    if ($env{'form.f'.$i} ne 'none') {
                   5014: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       5015: 	    }
                   5016: 	}
1.27      albertel 5017:     }
1.246     albertel 5018:     return %fields;
                   5019: }
                   5020: 
                   5021: sub csvuploadassign {
1.596.2.12.2.  1(raebur 5022:0):     my ($request,$symb) = @_;
1.246     albertel 5023:     if (!$symb) {return '';}
1.345     bowersj2 5024:     my $error_msg = '';
1.596.2.12.2.  3(raebur 5025:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   5026:8):     if ($datatoken ne '') {
                   5027:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   5028:8):     }
1.246     albertel 5029:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 5030:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 5031:     my %fields=&get_fields();
1.257     albertel 5032:     my $courseid=$env{'request.course.id'};
1.97      albertel 5033:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 5034:     my @notallowed;
1.41      ng       5035:     my @skipped;
1.596.2.4  raeburn  5036:     my @warnings;
1.41      ng       5037:     my $countdone=0;
                   5038:     foreach my $grade (@gradedata) {
                   5039: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5040: 	my $domain;
                   5041: 	if ($entries{$fields{'domain'}}) {
                   5042: 	    $domain=$entries{$fields{'domain'}};
                   5043: 	} else {
1.257     albertel 5044: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5045: 	}
1.243     albertel 5046: 	$domain=~s/\s//g;
1.41      ng       5047: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5048: 	$username=~s/\s//g;
1.243     albertel 5049: 	if (!$username) {
                   5050: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5051: 	    $id=~s/\s//g;
1.243     albertel 5052: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   5053: 	    $username=$ids{$id};
                   5054: 	}
1.41      ng       5055: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5056: 	    my $id=$entries{$fields{'ID'}};
                   5057: 	    $id=~s/\s//g;
                   5058: 	    if ($id) {
                   5059: 		push(@skipped,"$id:$domain");
                   5060: 	    } else {
                   5061: 		push(@skipped,"$username:$domain");
                   5062: 	    }
1.41      ng       5063: 	    next;
                   5064: 	}
1.108     albertel 5065: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5066: 	if (!&canmodify($usec)) {
                   5067: 	    push(@notallowed,"$username:$domain");
                   5068: 	    next;
                   5069: 	}
1.244     albertel 5070: 	my %points;
1.41      ng       5071: 	my %grades;
                   5072: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5073: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5074: 		$dest eq 'domain') { next; }
                   5075: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5076: 	    if ($dest=~/stores_(.*)_points/) {
                   5077: 		my $part=$1;
                   5078: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5079: 					      $symb,$domain,$username);
1.345     bowersj2 5080:                 if ($wgt) {
                   5081:                     $entries{$fields{$dest}}=~s/\s//g;
                   5082:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5083:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5084:                                           : 'correct_by_override';
1.596.2.4  raeburn  5085:                     if ($pcr>1) {
                   5086:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5087:                     }
1.345     bowersj2 5088:                     $grades{"resource.$part.awarded"}=$pcr;
                   5089:                     $grades{"resource.$part.solved"}=$award;
                   5090:                     $points{$part}=1;
                   5091:                 } else {
                   5092:                     $error_msg = "<br />" .
                   5093:                         &mt("Some point values were assigned"
                   5094:                             ." for problems with a weight "
                   5095:                             ."of zero. These values were "
                   5096:                             ."ignored.");
                   5097:                 }
1.244     albertel 5098: 	    } else {
                   5099: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5100: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5101: 		my $store_key=$dest;
                   5102: 		$store_key=~s/^stores/resource/;
                   5103: 		$store_key=~s/_/\./g;
                   5104: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5105: 	    }
1.41      ng       5106: 	}
1.596.2.12.2.  1(raebur 5107:0): 	if (! %grades) {
1.508     www      5108:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5109:         } else {
                   5110: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5111: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5112: 					   $env{'request.course.id'},
                   5113: 					   $domain,$username);
1.508     www      5114: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5115:0): # Successfully stored
1.508     www      5116: 	      $request->print('.');
1.596.2.4  raeburn  5117: # Remove from grading queue
                   5118:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5119:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5120:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5121:                                              $domain,$username);
1.508     www      5122: 	   } else {
                   5123: 	      $request->print("<p><span class=\"LC_error\">".
                   5124:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5125:                                   "$username:$domain",$result)."</span></p>");
                   5126: 	   }
                   5127: 	   $request->rflush();
                   5128: 	   $countdone++;
                   5129:         }
1.41      ng       5130:     }
1.570     www      5131:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5132:     if (@warnings) {
                   5133:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5134:         $request->print(join(', ',@warnings));
                   5135:     }
1.41      ng       5136:     if (@skipped) {
1.571     www      5137: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5138:         $request->print(join(', ',@skipped));
1.106     albertel 5139:     }
                   5140:     if (@notallowed) {
1.571     www      5141: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5142: 	$request->print(join(', ',@notallowed));
1.41      ng       5143:     }
1.106     albertel 5144:     $request->print("<br />\n");
1.345     bowersj2 5145:     return $error_msg;
1.26      albertel 5146: }
1.44      ng       5147: #------------- end of section for handling csv file upload ---------
                   5148: #
                   5149: #-------------------------------------------------------------------
                   5150: #
1.122     ng       5151: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5152: #
                   5153: #--- Select a page/sequence and a student to grade
1.68      ng       5154: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5155:0):     my ($request,$symb) = @_;
1.68      ng       5156: 
1.539     riegler  5157:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5158:6):     &js_escape(\$alertmsg);
          1(raebur 5159:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5160: 
                   5161: function checkPickOne(formname) {
1.76      ng       5162:     if (radioSelection(formname.student) == null) {
1.539     riegler  5163: 	alert("$alertmsg");
1.68      ng       5164: 	return;
                   5165:     }
1.125     ng       5166:     ptr = pullDownSelection(formname.selectpage);
                   5167:     formname.page.value = formname["page"+ptr].value;
                   5168:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5169:     formname.submit();
                   5170: }
                   5171: 
                   5172: LISTJAVASCRIPT
1.118     ng       5173:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5174:0): 
1.257     albertel 5175:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5176:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5177:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5178:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5179: 
1.398     albertel 5180:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5181: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5182: 
1.80      ng       5183:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5184:     my $map_error;
                   5185:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5186:     if ($map_error) {
                   5187:         $request->print(&navmap_errormsg());
                   5188:         return; 
                   5189:     }
1.137     albertel 5190:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5191: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5192: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5193: 
1.596.2.12.2.  1(raebur 5194:0):     # Collection of hidden fields
                   5195:0):     my $ctr=0;
1.70      ng       5196:     foreach (@$titles) {
                   5197: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5198: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5199: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5200: 	$ctr++;
                   5201:     }
1.72      ng       5202:     $result.='<input type="hidden" name="page" />'."\n".
                   5203: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5204: 
1.432     banghart 5205:     $result.=&build_section_inputs();
1.442     banghart 5206:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5207:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5208:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5209:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5210:0): 
                   5211:0):     # Show grading options
                   5212:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5213:0):     my $select = '<select name="selectpage">'."\n";
                   5214:0):     $ctr=0;
                   5215:0):     foreach (@$titles) {
                   5216:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5217:0):         $select.='<option value="'.$ctr.'"'.
                   5218:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5219:0):             '>'.$showtitle.'</option>'."\n";
                   5220:0):         $ctr++;
                   5221:0):     }
                   5222:0):     $select.= '</select>';
1.72      ng       5223: 
1.596.2.12.2.  1(raebur 5224:0):     $result.=
                   5225:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5226:0):        .$select
                   5227:0):        .&Apache::lonhtmlcommon::row_closure();
                   5228:0): 
                   5229:0):     $result.=
                   5230:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5231:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5232:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5233:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5234:0):            .&mt('yes').'</label>'."\n"
                   5235:0):        .&Apache::lonhtmlcommon::row_closure();
                   5236:0): 
                   5237:0):     $result.=
                   5238:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5239:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5240:0):            .&mt('none').' </label>'."\n"
                   5241:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5242:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5243:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5244:0):            .&mt('all submissions with details').' </label>'
                   5245:0):        .&Apache::lonhtmlcommon::row_closure();
                   5246:0): 
                   5247:0):     $result.=
                   5248:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5249:0):        .'<input type="text" name="CODE" value="" />'
                   5250:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5251:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5252: 
1.596.2.12.2.  1(raebur 5253:0):     # Show list of students to select for grading
                   5254:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5255:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5256: 
1.68      ng       5257:     $request->print($result);
                   5258: 
1.485     albertel 5259:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5260: 	&Apache::loncommon::start_data_table().
                   5261: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5262: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5263: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5264: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5265: 	'<th>'.&nameUserString('header').'</th>'.
                   5266: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5267:  
1.596.2.12.2.  8(raebur 5268:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5269:     my $ptr = 1;
1.294     albertel 5270:     foreach my $student (sort 
                   5271: 			 {
                   5272: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5273: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5274: 			     }
                   5275: 			     return $a cmp $b;
                   5276: 			 } (keys(%$fullname))) {
1.68      ng       5277: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5278: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5279:                                   : '</td>');
1.126     ng       5280: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5281: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5282: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5283: 	$studentTable.=
                   5284: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5285:                          : '');
1.68      ng       5286: 	$ptr++;
                   5287:     }
1.484     albertel 5288:     if ($ptr%2 == 0) {
                   5289: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5290: 	    &Apache::loncommon::end_data_table_row();
                   5291:     }
                   5292:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5293:     $studentTable.='<input type="button" '.
1.589     bisitz   5294:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5295: 
                   5296:     $request->print($studentTable);
                   5297: 
                   5298:     return '';
                   5299: }
                   5300: 
                   5301: sub getSymbMap {
1.582     raeburn  5302:     my ($map_error) = @_;
1.132     bowersj2 5303:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5304:     unless (ref($navmap)) {
                   5305:         if (ref($map_error)) {
                   5306:             $$map_error = 'navmap';
                   5307:         }
                   5308:         return;
                   5309:     }
1.68      ng       5310:     my %symbx = ();
                   5311:     my @titles = ();
1.117     bowersj2 5312:     my $minder = 0;
                   5313: 
                   5314:     # Gather every sequence that has problems.
1.240     albertel 5315:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5316: 					       1,0,1);
1.117     bowersj2 5317:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 5318: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 5319: 	    my $title = $minder.'.'.
                   5320: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5321: 	    push(@titles, $title); # minder in case two titles are identical
                   5322: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5323: 	    $minder++;
1.241     albertel 5324: 	}
1.68      ng       5325:     }
                   5326:     return \@titles,\%symbx;
                   5327: }
                   5328: 
1.72      ng       5329: #
                   5330: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5331: sub displayPage {
1.596.2.12.2.  1(raebur 5332:0):     my ($request,$symb) = @_;
1.257     albertel 5333:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5334:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5335:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5336:     my $pageTitle = $env{'form.page'};
1.103     albertel 5337:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5338:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5339:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5340: 
                   5341:     #need to make sure we have the correct data for later EXT calls, 
                   5342:     #thus invalidate the cache
                   5343:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5344:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5345:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5346:     &Apache::lonnet::clear_EXT_cache_status();
                   5347: 
1.103     albertel 5348:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5349:0): 	$request->print(
                   5350:0):             '<span class="LC_warning">'.
                   5351:0):             &mt('Unable to view requested student. ([_1])',
                   5352:0):                 $env{'form.student'}).
                   5353:0):             '</span>');
          8(raebur 5354:4):         return;
1.103     albertel 5355:     }
1.398     albertel 5356:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5357:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5358: 	'</h3>'."\n";
1.500     albertel 5359:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5360:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5361: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5362:     } else {
                   5363: 	delete($env{'form.CODE'});
                   5364:     }
1.71      ng       5365:     &sub_page_js($request);
                   5366:     $request->print($result);
                   5367: 
1.132     bowersj2 5368:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5369:     unless (ref($navmap)) {
                   5370:         $request->print(&navmap_errormsg());
                   5371:         return;
                   5372:     }
1.257     albertel 5373:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5374:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5375:     if (!$map) {
1.485     albertel 5376: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5377: 	return; 
                   5378:     }
1.68      ng       5379:     my $iterator = $navmap->getIterator($map->map_start(),
                   5380: 					$map->map_finish());
                   5381: 
1.71      ng       5382:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5383: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5384: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5385: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5386: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5387: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5388: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5389:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5390: 
1.382     albertel 5391:     if (defined($env{'form.CODE'})) {
                   5392: 	$studentTable.=
                   5393: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5394:     }
1.381     albertel 5395:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5396: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5397: 
1.594     bisitz   5398:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5399:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5400:         '</span>'."\n".
1.484     albertel 5401: 	&Apache::loncommon::start_data_table().
                   5402: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5403:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5404: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5405: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5406: 
1.329     albertel 5407:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5408:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5409:     $iterator->next(); # skip the first BEGIN_MAP
                   5410:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5411:     while ($depth > 0) {
1.68      ng       5412:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5413:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5414: 
1.385     albertel 5415:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5416: 	    my $parts = $curRes->parts();
1.68      ng       5417:             my $title = $curRes->compTitle();
1.71      ng       5418: 	    my $symbx = $curRes->symb();
1.484     albertel 5419: 	    $studentTable.=
                   5420: 		&Apache::loncommon::start_data_table_row().
                   5421: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5422: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5423:2): 		                        : '<br />('.&mt('[_1]parts',
                   5424:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5425: 		 ).
                   5426: 		 '</td>';
1.71      ng       5427: 	    $studentTable.='<td valign="top">';
1.382     albertel 5428: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5429: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5430: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5431: 					     undef,'both',\%form);
1.71      ng       5432: 	    } else {
1.382     albertel 5433: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5434: 		$companswer =~ s|<form(.*?)>||g;
                   5435: 		$companswer =~ s|</form>||g;
1.71      ng       5436: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5437: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5438: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5439: #		}
1.116     ng       5440: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5441: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5442: 	    }
                   5443: 
1.257     albertel 5444: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5445: 
1.257     albertel 5446: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5447: 		if ($record{'version'} eq '') {
1.485     albertel 5448: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5449: 		} else {
1.116     ng       5450: 		    my %responseType = ();
                   5451: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5452: 			my @responseIds =$curRes->responseIds($partid);
                   5453: 			my @responseType =$curRes->responseType($partid);
                   5454: 			my %responseIds;
                   5455: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5456: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5457: 			}
                   5458: 			$responseType{$partid} = \%responseIds;
1.116     ng       5459: 		    }
1.148     albertel 5460: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5461: 
1.71      ng       5462: 		}
1.257     albertel 5463: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5464: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5465:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5466: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5467: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5468:5): 									'','.submission',undef,
                   5469:5):                                                                         $usec,$identifier);
1.71      ng       5470:  
                   5471: 	    }
1.103     albertel 5472: 	    if (&canmodify($usec)) {
1.585     bisitz   5473:             $studentTable.=&gradeBox_start();
1.103     albertel 5474: 		foreach my $partid (@{$parts}) {
                   5475: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5476: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5477: 		    $question++;
                   5478: 		}
1.585     bisitz   5479:             $studentTable.=&gradeBox_end();
1.196     albertel 5480: 		$prob++;
1.71      ng       5481: 	    }
                   5482: 	    $studentTable.='</td></tr>';
1.68      ng       5483: 
1.103     albertel 5484: 	}
1.68      ng       5485:         $curRes = $iterator->next();
                   5486:     }
1.596.2.12.2.  6(raebur 5487:1):     my $disabled;
                   5488:1):     unless (&canmodify($usec)) {
                   5489:1):         $disabled = ' disabled="disabled"';
                   5490:1):     }
1.68      ng       5491: 
1.589     bisitz   5492:     $studentTable.=
                   5493:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5494:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5495:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5496:         '</form>'."\n";
1.71      ng       5497:     $request->print($studentTable);
                   5498: 
                   5499:     return '';
1.119     ng       5500: }
                   5501: 
                   5502: sub displaySubByDates {
1.148     albertel 5503:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5504:     my $isCODE=0;
1.335     albertel 5505:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5506:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5507:     my $studentTable=&Apache::loncommon::start_data_table().
                   5508: 	&Apache::loncommon::start_data_table_header_row().
                   5509: 	'<th>'.&mt('Date/Time').'</th>'.
                   5510: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5511:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5512: 	'<th>'.&mt('Submission').'</th>'.
                   5513: 	'<th>'.&mt('Status').'</th>'.
                   5514: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5515:     my ($version);
                   5516:     my %mark;
1.148     albertel 5517:     my %orders;
1.119     ng       5518:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5519:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5520: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5521:     }
1.335     albertel 5522: 
                   5523:     my $interaction;
1.525     raeburn  5524:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5525:5):     my (%lastrndseed,%lasttype);
1.119     ng       5526:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5527: 	my $timestamp = 
                   5528: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5529: 	if (exists($$record{$version.':resource.0.version'})) {
                   5530: 	    $interaction = $$record{$version.':resource.0.version'};
                   5531: 	}
1.596.2.12.2.  (raeburn 5532:):         if ($isTask && $env{'form.previousversion'}) {
                   5533:):             next unless ($interaction == $env{'form.previousversion'});
                   5534:):         }
1.335     albertel 5535: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5536: 		             : "$version:resource");
1.467     albertel 5537: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5538: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5539: 	if ($isCODE) {
                   5540: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5541: 	}
1.596.2.12.2.  (raeburn 5542:):         if ($isTask) {
                   5543:):             $studentTable.='<td>'.$interaction.'</td>';
                   5544:):         }
1.119     ng       5545: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5546: 	my @displaySub = ();
                   5547: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5548:             my ($hidden,$type);
                   5549:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5550:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5551:                 $hidden = 1;
                   5552:             }
1.596.2.12.2.  1(raebur 5553:0): 	    my @matchKey;
                   5554:0):             if ($isTask) {
                   5555:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
                   5556:0):             } else {
                   5557:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5558:0):             }
1.122     ng       5559: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5560: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5561: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5562: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5563: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5564:                     
1.335     albertel 5565: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5566: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5567:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5568:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5569:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5570:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5571:                                    .'</span>'
                   5572:                                    .' <b>';
1.596     raeburn  5573:                     if ($hidden) {
                   5574:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5575:                     } else {
1.596.2.2  raeburn  5576:                         my ($trial,$rndseed,$newvariation);
                   5577:                         if ($type eq 'randomizetry') {
                   5578:                             $trial = $$record{"$where.$partid.tries"};
                   5579:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5580:                         }
1.596     raeburn  5581: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5582: 			    $displaySub[0].=&mt('Trial not counted');
                   5583: 		        } else {
                   5584: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5585: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5586:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5587:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5588:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5589:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5590:                                 }
                   5591:                             }
1.596.2.12.2.  4(raebur 5592:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5593:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5594: 		        }
                   5595: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5596:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5597: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5598: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5599: 			    $orders{$partid}->{$responseId}=
                   5600: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5601:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5602: 		        }
1.596.2.2  raeburn  5603: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5604: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5605: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5606:                     }
1.147     albertel 5607: 		}
                   5608: 	    }
1.335     albertel 5609: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5610: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5611: 				    $$record{"$where.$partid.checkedin"},
                   5612: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5613: 					'<br />';
1.335     albertel 5614: 	    }
                   5615: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5616: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5617: 		    lc($$record{"$where.$partid.award"}).' '.
                   5618: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5619: 		    '<br />';
                   5620: 	    }
1.335     albertel 5621: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5622: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5623: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5624: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5625: 		$displaySub[2].=
                   5626: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5627: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5628: 	    }
                   5629: 	}
                   5630: 	# needed because old essay regrader has not parts info
                   5631: 	if (exists $$record{"$version:resource.regrader"}) {
                   5632: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5633: 	}
                   5634: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5635: 	if ($displaySub[2]) {
1.467     albertel 5636: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5637: 	}
1.467     albertel 5638: 	$studentTable.='&nbsp;</td>'.
                   5639: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5640:     }
1.467     albertel 5641:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5642:     return $studentTable;
1.71      ng       5643: }
                   5644: 
                   5645: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5646:0):     my ($request,$symb) = @_;
1.71      ng       5647: 
1.257     albertel 5648:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5649:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5650:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5651:     my $pageTitle = $env{'form.page'};
1.103     albertel 5652:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5653:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5654:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5655:     if (!&canmodify($usec)) {
1.526     raeburn  5656: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5657: 	return;
                   5658:     }
1.398     albertel 5659:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5660:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5661: 	'</h3>'."\n";
1.70      ng       5662: 
1.68      ng       5663:     $request->print($result);
                   5664: 
1.582     raeburn  5665: 
1.132     bowersj2 5666:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5667:     unless (ref($navmap)) {
                   5668:         $request->print(&navmap_errormsg());
                   5669:         return;
                   5670:     }
1.257     albertel 5671:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5672:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5673:     if (!$map) {
1.527     raeburn  5674: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5675: 	return; 
                   5676:     }
1.71      ng       5677:     my $iterator = $navmap->getIterator($map->map_start(),
                   5678: 					$map->map_finish());
1.70      ng       5679: 
1.484     albertel 5680:     my $studentTable=
                   5681: 	&Apache::loncommon::start_data_table().
                   5682: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5683: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5684: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5685: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5686: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5687: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5688: 
                   5689:     $iterator->next(); # skip the first BEGIN_MAP
                   5690:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5691:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5692:     while ($depth > 0) {
1.71      ng       5693:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5694:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5695: 
1.385     albertel 5696:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5697: 	    my $parts = $curRes->parts();
1.71      ng       5698:             my $title = $curRes->compTitle();
                   5699: 	    my $symbx = $curRes->symb();
1.484     albertel 5700: 	    $studentTable.=
                   5701: 		&Apache::loncommon::start_data_table_row().
                   5702: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5703: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5704:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5705: 		.')').'</td>';
1.71      ng       5706: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5707: 
                   5708: 	    my %newrecord=();
                   5709: 	    my @displayPts=();
1.269     raeburn  5710:             my %aggregate = ();
                   5711:             my $aggregateflag = 0;
1.596.2.12.2.  9(raebur 5712:1):             my %queueable;
          1(raebur 5713:5):             if ($env{'form.HIDE'.$prob}) {
                   5714:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5715:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5716:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5717:5):                 $hideflag += $numchgs;
                   5718:5):             }
1.71      ng       5719: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5720: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5721: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.596.2.12.2.  9(raebur 5722:1):                 my @types = $curRes->responseType($partid);
          8(raebur 5723:1):                 if (grep(/^essay$/,@types)) {
                   5724:1):                     $queueable{$partid} = 1;
                   5725:1):                 } else {
          9(raebur 5726:1):                     my @ids = $curRes->responseIds($partid);
          8(raebur 5727:1):                     for (my $i=0; $i < scalar(@ids); $i++) {
          9(raebur 5728:1):                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
          8(raebur 5729:1):                                                           '.handgrade',$symb);
                   5730:1):                         if (lc($hndgrd) eq 'yes') {
                   5731:1):                             $queueable{$partid} = 1;
                   5732:1):                             last;
                   5733:1):                         }
                   5734:1):                     }
                   5735:1):                 }
1.257     albertel 5736: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5737: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5738: 		my $partial = $newpts/$wgt;
                   5739: 		my $score;
                   5740: 		if ($partial > 0) {
                   5741: 		    $score = 'correct_by_override';
1.125     ng       5742: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5743: 		    $score = 'incorrect_by_override';
                   5744: 		}
1.257     albertel 5745: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5746: 		if ($dropMenu eq 'excused') {
1.71      ng       5747: 		    $partial = '';
                   5748: 		    $score = 'excused';
1.125     ng       5749: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5750: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5751: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5752: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5753: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5754: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5755: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5756: 		    $changeflag++;
                   5757: 		    $newpts = '';
1.269     raeburn  5758:                     
                   5759:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5760:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5761:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5762:                     if ($aggtries > 0) {
                   5763:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5764:                         $aggregateflag = 1;
                   5765:                     }
1.71      ng       5766: 		}
1.324     albertel 5767: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5768: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5769: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5770: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5771: 		    '&nbsp;<br />';
1.526     raeburn  5772: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5773: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5774: 		    '&nbsp;<br />';
1.71      ng       5775: 		$question++;
1.380     albertel 5776: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5777: 
1.71      ng       5778: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5779: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5780: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5781: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5782: 
                   5783: 		$changeflag++;
                   5784: 	    }
                   5785: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5786: 		my %record = 
                   5787: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5788: 					     $udom,$uname);
                   5789: 
                   5790: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5791: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5792: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5793: 		    $newrecord{'resource.CODE'} = '';
                   5794: 		}
1.257     albertel 5795: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5796: 					$udom,$uname);
1.382     albertel 5797: 		%record = &Apache::lonnet::restore($symbx,
                   5798: 						   $env{'request.course.id'},
                   5799: 						   $udom,$uname);
1.380     albertel 5800: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.596.2.12.2.  8(raebur 5801:1): 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5802: 	    }
1.380     albertel 5803: 	    
1.269     raeburn  5804:             if ($aggregateflag) {
                   5805:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5806:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5807:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5808:             }
1.125     ng       5809: 
1.71      ng       5810: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5811: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5812: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5813: 
1.196     albertel 5814: 	    $prob++;
1.68      ng       5815: 	}
1.71      ng       5816:         $curRes = $iterator->next();
1.68      ng       5817:     }
1.98      albertel 5818: 
1.484     albertel 5819:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5820:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5821: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5822:5): 		  $changeflag).'<br />');
                   5823:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5824:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5825:5):                      $hideflag).'<br />');
                   5826:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5827: 
1.70      ng       5828:     return '';
                   5829: }
                   5830: 
1.72      ng       5831: #-------- end of section for handling grading by page/sequence ---------
                   5832: #
                   5833: #-------------------------------------------------------------------
                   5834: 
1.581     www      5835: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5836: #
                   5837: #------ start of section for handling grading by page/sequence ---------
                   5838: 
1.423     albertel 5839: =pod
                   5840: 
                   5841: =head1 Bubble sheet grading routines
                   5842: 
1.424     albertel 5843:   For this documentation:
                   5844: 
                   5845:    'scanline' refers to the full line of characters
                   5846:    from the file that we are parsing that represents one entire sheet
                   5847: 
                   5848:    'bubble line' refers to the data
1.596.2.6  raeburn  5849:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5850: 
                   5851: 
1.596.2.6  raeburn  5852: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5853: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5854: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5855: one of the predefined configurations for what each scanline looks
                   5856: like.
                   5857: 
                   5858: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5859: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5860: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5861:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5862: invalid student/employee ID
1.424     albertel 5863: 
                   5864: If the CODE option is used that determines the randomization of the
1.556     weissno  5865: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5866: username:domain.
                   5867: 
                   5868: During the validation phase the instructor can choose to skip scanlines. 
                   5869: 
1.596.2.6  raeburn  5870: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5871: 
                   5872:   scantron_original_filename (unmodified original file)
                   5873:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5874:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5875: 
                   5876: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5877: correction information that isn't representable in the bubblesheet
1.424     albertel 5878: file (see &scantron_getfile() for more information)
                   5879: 
                   5880: After all scanlines are either valid, marked as valid or skipped, then
                   5881: foreach line foreach problem in the picked sequence, an ssi request is
                   5882: made that simulates a user submitting their selected letter(s) against
                   5883: the homework problem.
1.423     albertel 5884: 
                   5885: =over 4
                   5886: 
                   5887: 
                   5888: 
                   5889: =item defaultFormData
                   5890: 
                   5891:   Returns html hidden inputs used to hold context/default values.
                   5892: 
                   5893:  Arguments:
                   5894:   $symb - $symb of the current resource 
                   5895: 
                   5896: =cut
1.422     foxr     5897: 
1.81      albertel 5898: sub defaultFormData {
1.324     albertel 5899:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 5900:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5901: }
                   5902: 
1.447     foxr     5903: 
1.423     albertel 5904: =pod 
                   5905: 
                   5906: =item getSequenceDropDown
                   5907: 
                   5908:    Return html dropdown of possible sequences to grade
                   5909:  
                   5910:  Arguments:
1.582     raeburn  5911:    $symb - $symb of the current resource
                   5912:    $map_error - ref to scalar which will container error if
                   5913:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5914: 
                   5915: =cut
1.422     foxr     5916: 
1.75      albertel 5917: sub getSequenceDropDown {
1.582     raeburn  5918:     my ($symb,$map_error)=@_;
1.75      albertel 5919:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5920:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5921:     if (ref($map_error)) {
                   5922:         return if ($$map_error);
                   5923:     }
1.137     albertel 5924:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5925:     my $ctr=0;
                   5926:     foreach (@$titles) {
                   5927: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5928: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5929: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5930: 	    '>'.$showtitle.'</option>'."\n";
                   5931: 	$ctr++;
                   5932:     }
                   5933:     $result.= '</select>';
                   5934:     return $result;
                   5935: }
                   5936: 
1.495     albertel 5937: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5938:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5939: 
                   5940: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5941: 
1.509     raeburn  5942: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5943:                                    # matchresponse or rankresponse, where 
                   5944:                                    # an individual response can have multiple 
                   5945:                                    # lines
1.503     raeburn  5946: 
                   5947: my %responsetype_per_response;     # responsetype for each response
                   5948: 
1.596.2.12.2.  6(raebur 5949:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5950:3):                                    # numbered response. Needed when randomorder
                   5951:3):                                    # or randompick are in use. Key is ID, value 
                   5952:3):                                    # is response number.
                   5953:3): 
1.495     albertel 5954: # Save and restore the bubble lines array to the form env.
                   5955: 
                   5956: 
                   5957: sub save_bubble_lines {
                   5958:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5959: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5960: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5961: 	    $first_bubble_line{$line};
1.503     raeburn  5962:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5963:             $subdivided_bubble_lines{$line};
                   5964:         $env{"form.scantron.responsetype.$line"} =
                   5965:             $responsetype_per_response{$line};
1.495     albertel 5966:     }
1.596.2.12.2.  6(raebur 5967:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5968:3):         my $line = $masterseq_id_responsenum{$resid};
                   5969:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5970:3):     }
1.495     albertel 5971: }
                   5972: 
                   5973: 
                   5974: sub restore_bubble_lines {
                   5975:     my $line = 0;
                   5976:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5977:3):     %masterseq_id_responsenum = ();
1.495     albertel 5978:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5979: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5980: 	$bubble_lines_per_response{$line} = $value;
                   5981: 	$first_bubble_line{$line}  =
                   5982: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5983:         $subdivided_bubble_lines{$line} =
                   5984:             $env{"form.scantron.sub_bubblelines.$line"};
                   5985:         $responsetype_per_response{$line} =
                   5986:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5987:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5988:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5989: 	$line++;
                   5990:     }
                   5991: }
                   5992: 
1.423     albertel 5993: =pod 
                   5994: 
                   5995: =item scantron_filenames
                   5996: 
                   5997:    Returns a list of the scantron files in the current course 
                   5998: 
                   5999: =cut
1.422     foxr     6000: 
1.202     albertel 6001: sub scantron_filenames {
1.257     albertel 6002:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6003:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  6004:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 6005:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   6006:):                                                         $cname,$getpropath);
1.202     albertel 6007:     my @possiblenames;
1.596.2.12.2.  (raeburn 6008:):     if (ref($dirlist) eq 'ARRAY') {
                   6009:):         foreach my $filename (sort(@{$dirlist})) {
                   6010:): 	    ($filename)=split(/&/,$filename);
                   6011:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   6012:): 	    $filename=~s/^scantron_orig_//;
                   6013:): 	    push(@possiblenames,$filename);
                   6014:):         }
1.202     albertel 6015:     }
                   6016:     return @possiblenames;
                   6017: }
                   6018: 
1.423     albertel 6019: =pod 
                   6020: 
                   6021: =item scantron_uploads
                   6022: 
                   6023:    Returns  html drop-down list of scantron files in current course.
                   6024: 
                   6025:  Arguments:
                   6026:    $file2grade - filename to set as selected in the dropdown
                   6027: 
                   6028: =cut
1.422     foxr     6029: 
1.202     albertel 6030: sub scantron_uploads {
1.209     ng       6031:     my ($file2grade) = @_;
1.202     albertel 6032:     my $result=	'<select name="scantron_selectfile">';
                   6033:     $result.="<option></option>";
                   6034:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 6035: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 6036:     }
                   6037:     $result.="</select>";
                   6038:     return $result;
                   6039: }
                   6040: 
1.423     albertel 6041: =pod 
                   6042: 
                   6043: =item scantron_scantab
                   6044: 
                   6045:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6046:   file.
                   6047: 
                   6048: =cut
1.422     foxr     6049: 
1.82      albertel 6050: sub scantron_scantab {
                   6051:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6052:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 6053:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6054:     if (@lines > 0) {
                   6055:         foreach my $line (@lines) {
                   6056:             next if (($line =~ /^\#/) || ($line eq ''));
                   6057: 	    my ($name,$descrip)=split(/:/,$line);
                   6058: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6059:         }
1.82      albertel 6060:     }
                   6061:     $result.='</select>'."\n";
1.518     raeburn  6062:     return $result;
                   6063: }
                   6064: 
1.423     albertel 6065: =pod 
                   6066: 
                   6067: =item scantron_CODElist
                   6068: 
                   6069:   Returns html drop down of the saved CODE lists from current course,
                   6070:   generated from earlier printings.
                   6071: 
                   6072: =cut
1.422     foxr     6073: 
1.186     albertel 6074: sub scantron_CODElist {
1.257     albertel 6075:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6076:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6077:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6078:     my $namechoice='<option></option>';
1.225     albertel 6079:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6080: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6081: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6082: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6083:     }
                   6084:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6085:     return $namechoice;
                   6086: }
                   6087: 
1.423     albertel 6088: =pod 
                   6089: 
                   6090: =item scantron_CODEunique
                   6091: 
                   6092:   Returns the html for "Each CODE to be used once" radio.
                   6093: 
                   6094: =cut
1.422     foxr     6095: 
1.186     albertel 6096: sub scantron_CODEunique {
1.532     bisitz   6097:     my $result='<span class="LC_nobreak">
1.272     albertel 6098:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6099:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6100:                 </span>
1.532     bisitz   6101:                 <span class="LC_nobreak">
1.272     albertel 6102:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6103:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6104:                 </span>';
1.186     albertel 6105:     return $result;
                   6106: }
1.423     albertel 6107: 
                   6108: =pod 
                   6109: 
                   6110: =item scantron_selectphase
                   6111: 
1.596.2.6  raeburn  6112:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6113:   Allows for - starting a grading run.
1.424     albertel 6114:              - downloading existing scan data (original, corrected
1.423     albertel 6115:                                                 or skipped info)
                   6116: 
                   6117:              - uploading new scan data
                   6118: 
                   6119:  Arguments:
                   6120:   $r          - The Apache request object
                   6121:   $file2grade - name of the file that contain the scanned data to score
                   6122: 
                   6123: =cut
1.186     albertel 6124: 
1.75      albertel 6125: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6126:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6127:     if (!$symb) {return '';}
1.582     raeburn  6128:     my $map_error;
                   6129:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6130:     if ($map_error) {
                   6131:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6132:         return;
                   6133:     }
1.324     albertel 6134:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6135:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6136:     my $format_selector=&scantron_scantab();
1.186     albertel 6137:     my $CODE_selector=&scantron_CODElist();
                   6138:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6139:     my $result;
1.422     foxr     6140: 
1.513     foxr     6141:     $ssi_error = 0;
                   6142: 
1.596.2.4  raeburn  6143:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6144:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6145: 
                   6146:         # Chunk of form to prompt for a scantron file upload.
                   6147: 
                   6148:         $r->print('
1.596.2.12.2.  9(raebur 6149:9):     <br />');
                   6150:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6151:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6152:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6153:9):         &js_escape(\$alertmsg);
                   6154:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6155:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6156:     function checkUpload(formname) {
                   6157:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6158:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6159:             return false;
                   6160:         }
                   6161:         formname.submit();
1.596.2.12.2.  9(raebur 6162:9):     }'."\n".$formatjs));
                   6163:9):         $r->print('
1.596.2.4  raeburn  6164:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6165:                 '.$default_form_data.'
                   6166:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6167:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6168:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6169:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6170:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6171:9):                 <th>
                   6172:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6173:9):                 </th>
                   6174:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6175:9):               '.&Apache::loncommon::start_data_table_row().'
                   6176:9):             <td>
                   6177:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6178:9):         if ($formatoptions) {
                   6179:9):             $r->print('</td>
                   6180:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6181:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6182:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6183:9):                  </td>
                   6184:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6185:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6186:9):                  <td>'
                   6187:9):             );
                   6188:9):         } else {
                   6189:9):             $r->print(' <br />');
                   6190:9):         }
                   6191:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6192:9):               </td>
                   6193:9):              '.&Apache::loncommon::end_data_table_row().'
                   6194:9):              '.&Apache::loncommon::end_data_table().'
                   6195:9):              </form>'
                   6196:9):         );
1.596.2.4  raeburn  6197: 
                   6198:     }
                   6199: 
1.422     foxr     6200:     # Chunk of form to prompt for a file to grade and how:
                   6201: 
1.489     albertel 6202:     $result.= '
                   6203:     <br />
                   6204:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6205:     <input type="hidden" name="command" value="scantron_warning" />
                   6206:     '.$default_form_data.'
                   6207:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6208:        '.&Apache::loncommon::start_data_table_header_row().'
                   6209:             <th colspan="2">
1.492     albertel 6210:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6211:             </th>
                   6212:        '.&Apache::loncommon::end_data_table_header_row().'
                   6213:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6214:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6215:        '.&Apache::loncommon::end_data_table_row().'
                   6216:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6217:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6218:        '.&Apache::loncommon::end_data_table_row().'
                   6219:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6220:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6221:        '.&Apache::loncommon::end_data_table_row().'
                   6222:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6223:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6224:        '.&Apache::loncommon::end_data_table_row().'
                   6225:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6226:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6227:        '.&Apache::loncommon::end_data_table_row().'
                   6228:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6229: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6230:             <td>
1.492     albertel 6231: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6232:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6233:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6234: 	    </td>
1.489     albertel 6235:        '.&Apache::loncommon::end_data_table_row().'
                   6236:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6237:             <td colspan="2">
1.572     www      6238:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6239:             </td>
1.489     albertel 6240:        '.&Apache::loncommon::end_data_table_row().'
                   6241:     '.&Apache::loncommon::end_data_table().'
                   6242:     </form>
                   6243: ';
1.162     albertel 6244:    
                   6245:     $r->print($result);
                   6246: 
1.422     foxr     6247:     # Chunk of the form that prompts to view a scoring office file,
                   6248:     # corrected file, skipped records in a file.
                   6249: 
1.489     albertel 6250:     $r->print('
                   6251:    <br />
                   6252:    <form action="/adm/grades" name="scantron_download">
                   6253:      '.$default_form_data.'
                   6254:      <input type="hidden" name="command" value="scantron_download" />
                   6255:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6256:        '.&Apache::loncommon::start_data_table_header_row().'
                   6257:               <th>
1.492     albertel 6258:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6259:               </th>
                   6260:        '.&Apache::loncommon::end_data_table_header_row().'
                   6261:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6262:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6263:                 <br />
1.492     albertel 6264:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6265:        '.&Apache::loncommon::end_data_table_row().'
                   6266:      '.&Apache::loncommon::end_data_table().'
                   6267:    </form>
                   6268:    <br />
                   6269: ');
1.162     albertel 6270: 
1.457     banghart 6271:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6272: 
1.596.2.12.2.  8(raebur 6273:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6274:              $default_form_data."\n".
                   6275:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6276:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6277:              '<th colspan="2">
1.572     www      6278:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6279:              '</th>'."\n".
                   6280:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6281:               &Apache::loncommon::start_data_table_row()."\n".
                   6282:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6283:               '<td> '.$sequence_selector.' </td>'.
                   6284:               &Apache::loncommon::end_data_table_row()."\n".
                   6285:               &Apache::loncommon::start_data_table_row()."\n".
                   6286:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6287:               '<td> '.$file_selector.' </td>'."\n".
                   6288:               &Apache::loncommon::end_data_table_row()."\n".
                   6289:               &Apache::loncommon::start_data_table_row()."\n".
                   6290:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6291:               '<td> '.$format_selector.' </td>'."\n".
                   6292:               &Apache::loncommon::end_data_table_row()."\n".
                   6293:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6294:               '<td> '.&mt('Options').' </td>'."\n".
                   6295:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6296:               &Apache::loncommon::end_data_table_row()."\n".
                   6297:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6298:               '<td colspan="2">'."\n".
                   6299:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6300:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6301:               '</td>'."\n".
                   6302:               &Apache::loncommon::end_data_table_row()."\n".
                   6303:               &Apache::loncommon::end_data_table()."\n".
                   6304:               '</form><br />');
                   6305:     return;
1.75      albertel 6306: }
                   6307: 
1.423     albertel 6308: =pod 
                   6309: 
                   6310: =item username_to_idmap
                   6311: 
1.556     weissno  6312:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6313:     student username:domain.
                   6314: 
                   6315:   Arguments:
                   6316: 
                   6317:     $classlist - reference to the class list hash. This is a hash
                   6318:                  keyed by student name:domain  whose elements are references
1.424     albertel 6319:                  to arrays containing various chunks of information
1.423     albertel 6320:                  about the student. (See loncoursedata for more info).
                   6321: 
                   6322:   Returns
                   6323:     %idmap - the constructed hash
                   6324: 
                   6325: =cut
                   6326: 
1.82      albertel 6327: sub username_to_idmap {
                   6328:     my ($classlist)= @_;
                   6329:     my %idmap;
                   6330:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6331:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6332:5):         unless ($id eq '') {
                   6333:5):             if (!exists($idmap{$id})) {
                   6334:5):                 $idmap{$id} = $student;
                   6335:5):             } else {
                   6336:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6337:5):                 if ($status eq 'Active') {
                   6338:5):                     $idmap{$id} = $student;
                   6339:5):                 }
                   6340:5):             }
                   6341:5):         }
1.82      albertel 6342:     }
                   6343:     return %idmap;
                   6344: }
1.423     albertel 6345: 
                   6346: =pod
                   6347: 
1.424     albertel 6348: =item scantron_fixup_scanline
1.423     albertel 6349: 
                   6350:    Process a requested correction to a scanline.
                   6351: 
                   6352:   Arguments:
1.596.2.12.2.  9(raebur 6353:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6354:     $scan_data         - hash of correction information 
                   6355:                           (see &scantron_getfile())
                   6356:     $line              - existing scanline
                   6357:     $whichline         - line number of the passed in scanline
                   6358:     $field             - type of change to process 
                   6359:                          (either 
1.573     bisitz   6360:                           'ID'     -> correct the student/employee ID
1.423     albertel 6361:                           'CODE'   -> correct the CODE
                   6362:                           'answer' -> fixup the submitted answers)
                   6363:     
                   6364:    $args               - hash of additional info,
                   6365:                           - 'ID' 
                   6366:                                'newid' -> studentID to use in replacement
1.424     albertel 6367:                                           of existing one
1.423     albertel 6368:                           - 'CODE' 
                   6369:                                'CODE_ignore_dup' - set to true if duplicates
                   6370:                                                    should be ignored.
                   6371: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6372:                                         if the existing unfound code should
1.423     albertel 6373:                                         be used as is
                   6374:                           - 'answer'
                   6375:                                'response' - new answer or 'none' if blank
                   6376:                                'question' - the bubble line to change
1.503     raeburn  6377:                                'questionnum' - the question identifier,
                   6378:                                                may include subquestion. 
1.423     albertel 6379: 
                   6380:   Returns:
                   6381:     $line - the modified scanline
                   6382: 
                   6383:   Side effects: 
                   6384:     $scan_data - may be updated
                   6385: 
                   6386: =cut
                   6387: 
1.82      albertel 6388: 
1.157     albertel 6389: sub scantron_fixup_scanline {
                   6390:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6391:     if ($field eq 'ID') {
                   6392: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6393: 	    return ($line,1,'New value too large');
1.157     albertel 6394: 	}
                   6395: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6396: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6397: 				     $args->{'newid'});
                   6398: 	}
                   6399: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6400: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6401: 	if ($args->{'newid'}=~/^\s*$/) {
                   6402: 	    &scan_data($scan_data,"$whichline.user",
                   6403: 		       $args->{'username'}.':'.$args->{'domain'});
                   6404: 	}
1.186     albertel 6405:     } elsif ($field eq 'CODE') {
1.192     albertel 6406: 	if ($args->{'CODE_ignore_dup'}) {
                   6407: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6408: 	}
                   6409: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6410: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6411: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6412: 		return ($line,1,'New CODE value too large');
                   6413: 	    }
                   6414: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6415: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6416: 	    }
                   6417: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6418: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6419: 	}
1.157     albertel 6420:     } elsif ($field eq 'answer') {
1.497     foxr     6421: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6422: 	my $off=$scantron_config->{'Qoff'};
                   6423: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6424: 	my $answer=${off}x$length;
                   6425: 	if ($args->{'response'} eq 'none') {
                   6426: 	    &scan_data($scan_data,
1.503     raeburn  6427: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6428: 	} else {
                   6429: 	    if ($on eq 'letter') {
                   6430: 		my @alphabet=('A'..'Z');
                   6431: 		$answer=$alphabet[$args->{'response'}];
                   6432: 	    } elsif ($on eq 'number') {
                   6433: 		$answer=$args->{'response'}+1;
                   6434: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6435: 	    } else {
1.497     foxr     6436: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6437: 	    }
1.497     foxr     6438: 	    &scan_data($scan_data,
1.503     raeburn  6439: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6440: 	}
1.497     foxr     6441: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6442: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6443:     }
                   6444:     return $line;
                   6445: }
1.423     albertel 6446: 
                   6447: =pod
                   6448: 
                   6449: =item scan_data
                   6450: 
                   6451:     Edit or look up  an item in the scan_data hash.
                   6452: 
                   6453:   Arguments:
                   6454:     $scan_data  - The hash (see scantron_getfile)
                   6455:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6456:                   scantronfilename_key).
1.423     albertel 6457:     $data        - New value of the hash entry.
                   6458:     $delete      - If true, the entry is removed from the hash.
                   6459: 
                   6460:   Returns:
                   6461:     The new value of the hash table field (undefined if deleted).
                   6462: 
                   6463: =cut
                   6464: 
                   6465: 
1.157     albertel 6466: sub scan_data {
                   6467:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6468:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6469:     if (defined($value)) {
                   6470: 	$scan_data->{$filename.'_'.$key} = $value;
                   6471:     }
                   6472:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6473:     return $scan_data->{$filename.'_'.$key};
                   6474: }
1.423     albertel 6475: 
1.495     albertel 6476: # ----- These first few routines are general use routines.----
                   6477: 
                   6478: # Return the number of occurences of a pattern in a string.
                   6479: 
                   6480: sub occurence_count {
                   6481:     my ($string, $pattern) = @_;
                   6482: 
                   6483:     my @matches = ($string =~ /$pattern/g);
                   6484: 
                   6485:     return scalar(@matches);
                   6486: }
                   6487: 
                   6488: 
                   6489: # Take a string known to have digits and convert all the
                   6490: # digits into letters in the range J,A..I.
                   6491: 
                   6492: sub digits_to_letters {
                   6493:     my ($input) = @_;
                   6494: 
                   6495:     my @alphabet = ('J', 'A'..'I');
                   6496: 
                   6497:     my @input    = split(//, $input);
                   6498:     my $output ='';
                   6499:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6500: 	if ($input[$i] =~ /\d/) {
                   6501: 	    $output .= $alphabet[$input[$i]];
                   6502: 	} else {
                   6503: 	    $output .= $input[$i];
                   6504: 	}
                   6505:     }
                   6506:     return $output;
                   6507: }
                   6508: 
1.423     albertel 6509: =pod 
                   6510: 
                   6511: =item scantron_parse_scanline
                   6512: 
                   6513:   Decodes a scanline from the selected scantron file
                   6514: 
                   6515:  Arguments:
                   6516:     line             - The text of the scantron file line to process
                   6517:     whichline        - Line number
                   6518:     scantron_config  - Hash describing the format of the scantron lines.
                   6519:     scan_data        - Hash of extra information about the scanline
                   6520:                        (see scantron_getfile for more information)
                   6521:     just_header      - True if should not process question answers but only
                   6522:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6523:3):     randomorder      - True if randomorder in use
                   6524:3):     randompick       - True if randompick in use
                   6525:3):     sequence         - Exam folder URL
                   6526:3):     master_seq       - Ref to array containing symbs in exam folder
                   6527:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6528:3):                        (corresponding values are resource objects)
                   6529:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6530:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6531:3):                        are refs to an array of resource objects, ordered
                   6532:3):                        according to order used for CODE, when randomorder
                   6533:3):                        and or randompick are in use.
                   6534:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6535:3):                        for current line to question number used for same question
                   6536:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6537:3):     startline        - Ref to hash where key is question number (0 is first)
                   6538:3):                        and value is number of first bubble line for current 
                   6539:3):                        student or code-based randompick and/or randomorder.
                   6540:3):     totalref         - Ref of scalar used to score total number of bubble
                   6541:3):                        lines needed for responses in a scan line (used when
                   6542:3):                        randompick in use. 
                   6543:3): 
1.423     albertel 6544:  Returns:
                   6545:    Hash containing the result of parsing the scanline
                   6546: 
                   6547:    Keys are all proceeded by the string 'scantron.'
                   6548: 
                   6549:        CODE    - the CODE in use for this scanline
                   6550:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6551:                  by the operator
                   6552:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6553:                             CODEs were selected, but the usage has been
                   6554:                             forced by the operator
1.556     weissno  6555:        ID  - student/employee ID
1.423     albertel 6556:        PaperID - if used, the ID number printed on the sheet when the 
                   6557:                  paper was scanned
                   6558:        FirstName - first name from the sheet
                   6559:        LastName  - last name from the sheet
                   6560: 
                   6561:      if just_header was not true these key may also exist
                   6562: 
1.447     foxr     6563:        missingerror - a list of bubble ranges that are considered to be answers
                   6564:                       to a single question that don't have any bubbles filled in.
                   6565:                       Of the form questionnumber:firstbubblenumber:count.
                   6566:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6567:                       to a single question that have more than one bubble filled in.
                   6568:                       Of the form questionnumber::firstbubblenumber:count
                   6569:    
                   6570:                 In the above, count is the number of bubble responses in the
                   6571:                 input line needed to represent the possible answers to the question.
                   6572:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6573:                 per line would have count = 2.
                   6574: 
1.423     albertel 6575:        maxquest     - the number of the last bubble line that was parsed
                   6576: 
                   6577:        (<number> starts at 1)
                   6578:        <number>.answer - zero or more letters representing the selected
                   6579:                          letters from the scanline for the bubble line 
                   6580:                          <number>.
                   6581:                          if blank there was either no bubble or there where
                   6582:                          multiple bubbles, (consult the keys missingerror and
                   6583:                          doubleerror if this is an error condition)
                   6584: 
                   6585: =cut
                   6586: 
1.82      albertel 6587: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6588:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6589:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6590:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6591: 
1.82      albertel 6592:     my %record;
1.596.2.12.2.  6(raebur 6593:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6594:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6595: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6596: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6597: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6598: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6599: 	    $record{'scantron.CODE'}=substr($data,
                   6600: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6601: 					    $$scantron_config{'CODElength'});
1.191     albertel 6602: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6603: 		$record{'scantron.useCODE'}=1;
                   6604: 	    }
1.192     albertel 6605: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6606: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6607: 	    }
1.82      albertel 6608: 	} else {
                   6609: 	    #FIXME interpret first N questions
                   6610: 	}
                   6611:     }
1.83      albertel 6612:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6613: 				  $$scantron_config{'IDlength'});
1.157     albertel 6614:     $record{'scantron.PaperID'}=
                   6615: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6616: 	       $$scantron_config{'PaperIDlength'});
                   6617:     $record{'scantron.FirstName'}=
                   6618: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6619: 	       $$scantron_config{'FirstNamelength'});
                   6620:     $record{'scantron.LastName'}=
                   6621: 	substr($data,$$scantron_config{'LastName'}-1,
                   6622: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6623:     if ($just_header) { return \%record; }
1.194     albertel 6624: 
1.82      albertel 6625:     my @alphabet=('A'..'Z');
                   6626:     my $questnum=0;
1.447     foxr     6627:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6628: 
1.596.2.12.2.  6(raebur 6629:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6630:3):     if ($randompick || $randomorder) {
                   6631:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6632:3):                                          $master_seq,$symb_to_resource,
                   6633:3):                                          $partids_by_symb,$orderedforcode,
                   6634:3):                                          $respnumlookup,$startline);
                   6635:3):         if ($total) {
                   6636:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6637:3):         }
                   6638:3):         if (ref($totalref)) {
                   6639:3):             $$totalref = $total;
                   6640:3):         }
                   6641:3):     }
                   6642:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6643:     chomp($questions);		# Get rid of any trailing \n.
                   6644:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6645:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6646:3):         my $answers_needed;
                   6647:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6648:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6649:3):         } else {
                   6650:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6651:3):         }
1.503     raeburn  6652:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6653:                              || 1;
                   6654:         $questnum++;
                   6655:         my $quest_id = $questnum;
                   6656:         my $currentquest = substr($questions,0,$answer_length);
                   6657:         $questions       = substr($questions,$answer_length);
                   6658:         if (length($currentquest) < $answer_length) { next; }
                   6659: 
1.596.2.12.2.  6(raebur 6660:3):         my $subdivided;
                   6661:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6662:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6663:3):         } else {
                   6664:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6665:3):         }
                   6666:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6667:             my $subquestnum = 1;
                   6668:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6669:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6670:             foreach my $subans (@subanswers_needed) {
                   6671:                 my $subans_length =
                   6672:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6673:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6674:                 $subquestions   = substr($subquestions,$subans_length);
                   6675:                 $quest_id = "$questnum.$subquestnum";
                   6676:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6677:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6678:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6679:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6680:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6681:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6682:                 } else {
                   6683:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6684:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6685:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6686:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6687:                 }
                   6688:                 $subquestnum ++;
                   6689:             }
                   6690:         } else {
                   6691:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6692:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6693:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6694:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6695:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6696:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6697:             } else {
                   6698:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6699:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6700:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6701:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6702:             }
                   6703:         }
                   6704:     }
                   6705:     $record{'scantron.maxquest'}=$questnum;
                   6706:     return \%record;
                   6707: }
1.447     foxr     6708: 
1.596.2.12.2.  6(raebur 6709:3): sub get_master_seq {
          0(raebur 6710:2):     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
          6(raebur 6711:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6712:3):                    (ref($symb_to_resource) eq 'HASH'));
          0(raebur 6713:2):     if ($need_symb_in_map) {
                   6714:2):         return unless (ref($symb_for_examcode) eq 'HASH');
                   6715:2):     }
          6(raebur 6716:3):     my $resource_error;
                   6717:3):     foreach my $resource (@{$resources}) {
                   6718:3):         my $ressymb;
                   6719:3):         if (ref($resource)) {
                   6720:3):             $ressymb = $resource->symb();
                   6721:3):             push(@{$master_seq},$ressymb);
                   6722:3):             $symb_to_resource->{$ressymb} = $resource;
          0(raebur 6723:2):             if ($need_symb_in_map) {
                   6724:2):                 unless ($resource->is_map()) {
                   6725:2):                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6726:2):                     unless (exists($symb_for_examcode->{$map})) {
                   6727:2):                         $symb_for_examcode->{$map} = $ressymb;
                   6728:2):                     }
                   6729:2):                 }
                   6730:2):             }
          6(raebur 6731:3):         } else {
                   6732:3):             $resource_error = 1;
                   6733:3):             last;
                   6734:3):         }
                   6735:3):     }
                   6736:3):     return $resource_error;
                   6737:3): }
                   6738:3): 
                   6739:3): sub get_respnum_lookups {
                   6740:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6741:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6742:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6743:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6744:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6745:3):                    (ref($startline) eq 'HASH'));
                   6746:3):     my ($user,$scancode);
                   6747:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6748:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6749:3):         $scancode = $record->{'scantron.CODE'};
                   6750:3):     } else {
                   6751:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6752:3):     }
                   6753:3):     my @mapresources =
                   6754:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6755:3):                      $orderedforcode);
                   6756:3):     my $total = 0;
                   6757:3):     my $count = 0;
                   6758:3):     foreach my $resource (@mapresources) {
                   6759:3):         my $id = $resource->id();
                   6760:3):         my $symb = $resource->symb();
                   6761:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6762:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6763:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6764:3):                 if ($respnum ne '') {
                   6765:3):                     $respnumlookup->{$count} = $respnum;
                   6766:3):                     $startline->{$count} = $total;
                   6767:3):                     $total += $bubble_lines_per_response{$respnum};
                   6768:3):                     $count ++;
                   6769:3):                 }
                   6770:3):             }
                   6771:3):         }
                   6772:3):     }
                   6773:3):     return $total;
                   6774:3): }
                   6775:3): 
1.503     raeburn  6776: sub scantron_validator_lettnum {
                   6777:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6778:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6779:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6780: 
                   6781:     # Qon 'letter' implies for each slot in currquest we have:
                   6782:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6783:     #    about anything else (esp. a value of Qoff) for missing
                   6784:     #    bubbles.
                   6785:     #
                   6786:     # Qon 'number' implies each slot gives a digit that indexes the
                   6787:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6788:     #    and * or ? for double bubbles on a single line.
                   6789:     #
1.447     foxr     6790: 
1.503     raeburn  6791:     my $matchon;
                   6792:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6793:         $matchon = '[A-Z]';
                   6794:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6795:         $matchon = '\d';
                   6796:     }
                   6797:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6798:3):     my $responsenum = $questnum-1;
                   6799:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6800:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6801:3):     }
                   6802:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6803:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6804:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6805:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6806:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6807:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6808:         my @singlelines = split('',$currquest);
                   6809:         foreach my $entry (@singlelines) {
                   6810:             $occurrences = &occurence_count($entry,$matchon);
                   6811:             if ($occurrences > 1) {
                   6812:                 last;
                   6813:             }
1.596.2.12.2.  6(raebur 6814:3):         }
1.503     raeburn  6815:     } else {
                   6816:         $occurrences = &occurence_count($currquest,$matchon); 
                   6817:     }
                   6818:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6819:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6820:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6821:             my $bubble = substr($currquest,$ans,1);
                   6822:             if ($bubble =~ /$matchon/ ) {
                   6823:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6824:                     if ($bubble == 0) {
                   6825:                         $bubble = 10; 
                   6826:                     }
                   6827:                     $record->{"scantron.$ansnum.answer"} = 
                   6828:                         $alphabet->[$bubble-1];
                   6829:                 } else {
                   6830:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6831:                 }
                   6832:             } else {
                   6833:                 $record->{"scantron.$ansnum.answer"}='';
                   6834:             }
                   6835:             $ansnum++;
                   6836:         }
                   6837:     } elsif (!defined($currquest)
                   6838:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6839:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6840:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6841:             $record->{"scantron.$ansnum.answer"}='';
                   6842:             $ansnum++;
                   6843:         }
                   6844:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6845:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6846:         }
                   6847:     } else {
                   6848:         if ($$scantron_config{'Qon'} eq 'number') {
                   6849:             $currquest = &digits_to_letters($currquest);            
                   6850:         }
                   6851:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6852:             my $bubble = substr($currquest,$ans,1);
                   6853:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6854:             $ansnum++;
                   6855:         }
                   6856:     }
                   6857:     return $ansnum;
                   6858: }
1.447     foxr     6859: 
1.503     raeburn  6860: sub scantron_validator_positional {
                   6861:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6862:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6863:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6864: 
1.503     raeburn  6865:     # Otherwise there's a positional notation;
                   6866:     # each bubble line requires Qlength items, and there are filled in
                   6867:     # bubbles for each case where there 'Qon' characters.
                   6868:     #
1.447     foxr     6869: 
1.503     raeburn  6870:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6871: 
1.503     raeburn  6872:     # If the split only gives us one element.. the full length of the
                   6873:     # answer string, no bubbles are filled in:
1.447     foxr     6874: 
1.507     raeburn  6875:     if ($answers_needed eq '') {
                   6876:         return;
                   6877:     }
                   6878: 
1.503     raeburn  6879:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6880:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6881:             $record->{"scantron.$ansnum.answer"}='';
                   6882:             $ansnum++;
                   6883:         }
                   6884:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6885:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6886:         }
                   6887:     } elsif (scalar(@array) == 2) {
                   6888:         my $location = length($array[0]);
                   6889:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6890:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6891:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6892:             if ($ans eq $line_num) {
                   6893:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6894:             } else {
                   6895:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6896:             }
                   6897:             $ansnum++;
                   6898:          }
                   6899:     } else {
                   6900:         #  If there's more than one instance of a bubble character
                   6901:         #  That's a double bubble; with positional notation we can
                   6902:         #  record all the bubbles filled in as well as the
                   6903:         #  fact this response consists of multiple bubbles.
                   6904:         #
1.596.2.12.2.  6(raebur 6905:3):         my $responsenum = $questnum-1;
                   6906:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6907:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6908:3):         }
                   6909:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6910:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6911:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6912:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6913:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6914:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6915:             my $doubleerror = 0;
                   6916:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6917:                    (!$doubleerror)) {
                   6918:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6919:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6920:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6921:                if (length(@currarray) > 2) {
                   6922:                    $doubleerror = 1;
                   6923:                } 
                   6924:             }
                   6925:             if ($doubleerror) {
                   6926:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6927:             }
                   6928:         } else {
                   6929:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6930:         }
                   6931:         my $item = $ansnum;
                   6932:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6933:             $record->{"scantron.$item.answer"} = '';
                   6934:             $item ++;
                   6935:         }
1.447     foxr     6936: 
1.503     raeburn  6937:         my @ans=@array;
                   6938:         my $i=0;
                   6939:         my $increment = 0;
                   6940:         while ($#ans) {
                   6941:             $i+=length($ans[0]) + $increment;
                   6942:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6943:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6944:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6945:             shift(@ans);
                   6946:             $increment = 1;
                   6947:         }
                   6948:         $ansnum += $answers_needed;
1.82      albertel 6949:     }
1.503     raeburn  6950:     return $ansnum;
1.82      albertel 6951: }
                   6952: 
1.423     albertel 6953: =pod
                   6954: 
                   6955: =item scantron_add_delay
                   6956: 
                   6957:    Adds an error message that occurred during the grading phase to a
                   6958:    queue of messages to be shown after grading pass is complete
                   6959: 
                   6960:  Arguments:
1.424     albertel 6961:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6962:    $scanline    - the scanline that caused the error
                   6963:    $errormesage - the error message
                   6964:    $errorcode   - a numeric code for the error
                   6965: 
                   6966:  Side Effects:
1.424     albertel 6967:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6968: 
                   6969: =cut
                   6970: 
1.82      albertel 6971: sub scantron_add_delay {
1.140     albertel 6972:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6973:     push(@$delayqueue,
                   6974: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6975: 	  'ecode' => $errorcode }
                   6976: 	 );
1.82      albertel 6977: }
                   6978: 
1.423     albertel 6979: =pod
                   6980: 
                   6981: =item scantron_find_student
                   6982: 
1.424     albertel 6983:    Finds the username for the current scanline
                   6984: 
                   6985:   Arguments:
                   6986:    $scantron_record - hash result from scantron_parse_scanline
                   6987:    $scan_data       - hash of correction information 
                   6988:                       (see &scantron_getfile() form more information)
                   6989:    $idmap           - hash from &username_to_idmap()
                   6990:    $line            - number of current scanline
                   6991:  
                   6992:   Returns:
                   6993:    Either 'username:domain' or undef if unknown
                   6994: 
1.423     albertel 6995: =cut
                   6996: 
1.82      albertel 6997: sub scantron_find_student {
1.157     albertel 6998:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6999:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 7000:     if ($scanID =~ /^\s*$/) {
                   7001:  	return &scan_data($scan_data,"$line.user");
                   7002:     }
1.83      albertel 7003:     foreach my $id (keys(%$idmap)) {
1.157     albertel 7004:  	if (lc($id) eq lc($scanID)) {
                   7005:  	    return $$idmap{$id};
                   7006:  	}
1.83      albertel 7007:     }
                   7008:     return undef;
                   7009: }
                   7010: 
1.423     albertel 7011: =pod
                   7012: 
                   7013: =item scantron_filter
                   7014: 
1.424     albertel 7015:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   7016:    hidden resources was selected
                   7017: 
1.423     albertel 7018: =cut
                   7019: 
1.83      albertel 7020: sub scantron_filter {
                   7021:     my ($curres)=@_;
1.331     albertel 7022: 
                   7023:     if (ref($curres) && $curres->is_problem()) {
                   7024: 	# if the user has asked to not have either hidden
                   7025: 	# or 'randomout' controlled resources to be graded
                   7026: 	# don't include them
                   7027: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7028: 	    && $curres->randomout) {
                   7029: 	    return 0;
                   7030: 	}
1.83      albertel 7031: 	return 1;
                   7032:     }
                   7033:     return 0;
1.82      albertel 7034: }
                   7035: 
1.423     albertel 7036: =pod
                   7037: 
                   7038: =item scantron_process_corrections
                   7039: 
1.424     albertel 7040:    Gets correction information out of submitted form data and corrects
                   7041:    the scanline
                   7042: 
1.423     albertel 7043: =cut
                   7044: 
1.157     albertel 7045: sub scantron_process_corrections {
                   7046:     my ($r) = @_;
1.596.2.12.2.  9(raebur 7047:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7048:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7049:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7050:     my $which=$env{'form.scantron_line'};
1.200     albertel 7051:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7052:     my ($skip,$err,$errmsg);
1.257     albertel 7053:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7054: 	$skip=1;
1.257     albertel 7055:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7056: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7057: 	    $env{'form.scantron_domain'};
1.157     albertel 7058: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7059: 	($line,$err,$errmsg)=
                   7060: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7061: 				     'ID',{'newid'=>$newid,
1.257     albertel 7062: 				    'username'=>$env{'form.scantron_username'},
                   7063: 				    'domain'=>$env{'form.scantron_domain'}});
                   7064:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7065: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7066: 	my $newCODE;
1.192     albertel 7067: 	my %args;
1.190     albertel 7068: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7069: 	    $newCODE='use_unfound';
1.190     albertel 7070: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7071: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7072: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7073: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7074: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7075: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7076: 	}
1.257     albertel 7077: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7078: 	    $args{'CODE_ignore_dup'}=1;
                   7079: 	}
                   7080: 	$args{'CODE'}=$newCODE;
1.186     albertel 7081: 	($line,$err,$errmsg)=
                   7082: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7083: 				     'CODE',\%args);
1.257     albertel 7084:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7085: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7086: 	    ($line,$err,$errmsg)=
                   7087: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7088: 					 $which,'answer',
                   7089: 					 { 'question'=>$question,
1.503     raeburn  7090: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7091:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7092: 	    if ($err) { last; }
                   7093: 	}
                   7094:     }
                   7095:     if ($err) {
1.596.2.12.2.  0(raebur 7096:3): 	$r->print(
                   7097:3):             '<p class="LC_error">'
                   7098:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7099:3):                 $errmsg)
          1(raebur 7100:3):            .'</p>');
1.157     albertel 7101:     } else {
1.200     albertel 7102: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7103: 	&scantron_putfile($scanlines,$scan_data);
                   7104:     }
                   7105: }
                   7106: 
1.423     albertel 7107: =pod
                   7108: 
                   7109: =item reset_skipping_status
                   7110: 
1.424     albertel 7111:    Forgets the current set of remember skipped scanlines (and thus
                   7112:    reverts back to considering all lines in the
                   7113:    scantron_skipped_<filename> file)
                   7114: 
1.423     albertel 7115: =cut
                   7116: 
1.200     albertel 7117: sub reset_skipping_status {
                   7118:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7119:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7120:     &scantron_putfile(undef,$scan_data);
                   7121: }
                   7122: 
1.423     albertel 7123: =pod
                   7124: 
                   7125: =item start_skipping
                   7126: 
1.424     albertel 7127:    Marks a scanline to be skipped. 
                   7128: 
1.423     albertel 7129: =cut
                   7130: 
1.376     albertel 7131: sub start_skipping {
1.200     albertel 7132:     my ($scan_data,$i)=@_;
                   7133:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7134:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7135: 	$remembered{$i}=2;
                   7136:     } else {
                   7137: 	$remembered{$i}=1;
                   7138:     }
1.200     albertel 7139:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7140: }
                   7141: 
1.423     albertel 7142: =pod
                   7143: 
                   7144: =item should_be_skipped
                   7145: 
1.424     albertel 7146:    Checks whether a scanline should be skipped.
                   7147: 
1.423     albertel 7148: =cut
                   7149: 
1.200     albertel 7150: sub should_be_skipped {
1.376     albertel 7151:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7152:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7153: 	# not redoing old skips
1.376     albertel 7154: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7155: 	return 0;
                   7156:     }
                   7157:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7158: 
                   7159:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7160: 	return 0;
                   7161:     }
1.200     albertel 7162:     return 1;
                   7163: }
                   7164: 
1.423     albertel 7165: =pod
                   7166: 
                   7167: =item remember_current_skipped
                   7168: 
1.424     albertel 7169:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7170:    file and remembers them into scan_data for later use.
                   7171: 
1.423     albertel 7172: =cut
                   7173: 
1.200     albertel 7174: sub remember_current_skipped {
                   7175:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7176:     my %to_remember;
                   7177:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7178: 	if ($scanlines->{'skipped'}[$i]) {
                   7179: 	    $to_remember{$i}=1;
                   7180: 	}
                   7181:     }
1.376     albertel 7182: 
1.200     albertel 7183:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7184:     &scantron_putfile(undef,$scan_data);
                   7185: }
                   7186: 
1.423     albertel 7187: =pod
                   7188: 
                   7189: =item check_for_error
                   7190: 
1.424     albertel 7191:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7192:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7193:     something went wrong.
                   7194: 
1.423     albertel 7195: =cut
                   7196: 
1.200     albertel 7197: sub check_for_error {
                   7198:     my ($r,$result)=@_;
                   7199:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7200: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7201:     }
                   7202: }
1.157     albertel 7203: 
1.423     albertel 7204: =pod
                   7205: 
                   7206: =item scantron_warning_screen
                   7207: 
1.424     albertel 7208:    Interstitial screen to make sure the operator has selected the
                   7209:    correct options before we start the validation phase.
                   7210: 
1.423     albertel 7211: =cut
                   7212: 
1.203     albertel 7213: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7214:0):     my ($button_text,$symb)=@_;
1.257     albertel 7215:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7216:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7217:     my $CODElist;
1.284     albertel 7218:     if ($scantron_config{'CODElocation'} &&
                   7219: 	$scantron_config{'CODEstart'} &&
                   7220: 	$scantron_config{'CODElength'}) {
                   7221: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7222:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7223: 	$CODElist=
1.492     albertel 7224: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7225: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7226:     }
1.596.2.12.2.  (raeburn 7227:):     my $lastbubblepoints;
                   7228:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7229:):         $lastbubblepoints =
                   7230:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7231:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7232:):     }
1.492     albertel 7233:     return ('
1.203     albertel 7234: <p>
1.492     albertel 7235: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7236:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7237: </p>
                   7238: <table>
1.492     albertel 7239: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7240: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.596.2.12.2.  (raeburn 7241:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7242: </table>
1.596.2.12.2.  1(raebur 7243:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7244:0): '.&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.203     albertel 7245: 
                   7246: <br />
1.492     albertel 7247: ');
1.203     albertel 7248: }
                   7249: 
1.423     albertel 7250: =pod
                   7251: 
                   7252: =item scantron_do_warning
                   7253: 
1.424     albertel 7254:    Check if the operator has picked something for all required
                   7255:    fields. Error out if something is missing.
                   7256: 
1.423     albertel 7257: =cut
                   7258: 
1.203     albertel 7259: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7260:0):     my ($r,$symb)=@_;
1.203     albertel 7261:     if (!$symb) {return '';}
1.324     albertel 7262:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7263:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7264:     if ( $env{'form.selectpage'} eq '' ||
                   7265: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7266: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7267: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7268: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7269: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7270: 	} 
1.257     albertel 7271: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7272: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.237     albertel 7273: 	} 
1.257     albertel 7274: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7275: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 7276: 	} 
                   7277:     } else {
1.596.2.12.2.  1(raebur 7278:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7279:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7280: 	$r->print('
1.596.2.12.2.  (raeburn 7281:): '.$warning.$bubbledbyhand.'
1.492     albertel 7282: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7283: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7284: ');
1.237     albertel 7285:     }
1.596.2.12.2.  1(raebur 7286:0):     $r->print("</form><br />");
1.203     albertel 7287:     return '';
                   7288: }
                   7289: 
1.423     albertel 7290: =pod
                   7291: 
                   7292: =item scantron_form_start
                   7293: 
1.424     albertel 7294:     html hidden input for remembering all selected grading options
                   7295: 
1.423     albertel 7296: =cut
                   7297: 
1.203     albertel 7298: sub scantron_form_start {
                   7299:     my ($max_bubble)=@_;
                   7300:     my $result= <<SCANTRONFORM;
                   7301: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7302:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7303:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7304:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7305:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7306:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7307:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7308:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7309:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7310:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7311: SCANTRONFORM
1.447     foxr     7312: 
                   7313:   my $line = 0;
                   7314:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7315:        my $chunk =
                   7316: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7317:        $chunk .=
                   7318: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7319:        $chunk .= 
                   7320:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7321:        $chunk .=
                   7322:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7323:3):        $chunk .=
                   7324:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7325:        $result .= $chunk;
                   7326:        $line++;
1.596.2.12.2.  6(raebur 7327:3):     }
1.203     albertel 7328:     return $result;
                   7329: }
                   7330: 
1.423     albertel 7331: =pod
                   7332: 
                   7333: =item scantron_validate_file
                   7334: 
1.596.2.6  raeburn  7335:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7336: 
                   7337:     Also processes any necessary information resets that need to
                   7338:     occur before validation begins (ignore previous corrections,
                   7339:     restarting the skipped records processing)
                   7340: 
1.423     albertel 7341: =cut
                   7342: 
1.157     albertel 7343: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7344:0):     my ($r,$symb) = @_;
1.157     albertel 7345:     if (!$symb) {return '';}
1.324     albertel 7346:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7347:     
1.596.2.12.2.  0(raebur 7348:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7349:     # them when doing the corrections reset
1.257     albertel 7350:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7351: 	&reset_skipping_status();
                   7352:     }
1.257     albertel 7353:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7354: 	&remember_current_skipped();
1.257     albertel 7355: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7356:     }
                   7357: 
1.257     albertel 7358:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7359: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7360: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7361: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7362: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7363:     }
1.200     albertel 7364: 
1.257     albertel 7365:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7366: 	&scantron_process_corrections($r);
                   7367:     }
1.503     raeburn  7368:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7369:     #get the student pick code ready
                   7370:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7371:     my $nav_error;
1.596.2.12.2.  9(raebur 7372:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7373:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7374:     if ($nav_error) {
                   7375:         $r->print(&navmap_errormsg());
                   7376:         return '';
                   7377:     }
1.203     albertel 7378:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7379:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7380:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7381:):     }
1.157     albertel 7382:     $r->print($result);
                   7383:     
1.334     albertel 7384:     my @validate_phases=( 'sequence',
                   7385: 			  'ID',
1.157     albertel 7386: 			  'CODE',
                   7387: 			  'doublebubble',
                   7388: 			  'missingbubbles');
1.257     albertel 7389:     if (!$env{'form.validatepass'}) {
                   7390: 	$env{'form.validatepass'} = 0;
1.157     albertel 7391:     }
1.257     albertel 7392:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7393: 
1.448     foxr     7394: 
1.157     albertel 7395:     my $stop=0;
                   7396:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7397: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7398: 	$r->rflush();
1.596.2.12.2.  6(raebur 7399:3): 
1.157     albertel 7400: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7401: 	{
                   7402: 	    no strict 'refs';
                   7403: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7404: 	}
                   7405:     }
                   7406:     if (!$stop) {
1.596.2.12.2.  1(raebur 7407:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7408: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7409:                   $warning.
                   7410:                   &mt('Perform verification for each student after storage of submissions?').
                   7411:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7412:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7413:                   ('&nbsp;'x3).'<label>'.
                   7414:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7415:                   '</label></span><br />'.
                   7416:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7417:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7418:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7419:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7420:     } else {
                   7421: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7422: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7423:     }
                   7424:     if ($stop) {
1.334     albertel 7425: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7426: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7427: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7428: 
1.596.2.12.2.  1(raebur 7429:0):             $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 7430: 	} else {
1.503     raeburn  7431:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7432: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7433:             } else {
1.539     riegler  7434:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7435:             }
1.492     albertel 7436: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7437: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7438: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7439: 	}
1.157     albertel 7440:     }
1.596.2.12.2.  1(raebur 7441:0):     $r->print(" </form><br />");
1.157     albertel 7442:     return '';
                   7443: }
                   7444: 
1.423     albertel 7445: 
                   7446: =pod
                   7447: 
                   7448: =item scantron_remove_file
                   7449: 
1.596.2.6  raeburn  7450:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7451:    scantron_original_<filename> is never removed
                   7452: 
                   7453: 
1.423     albertel 7454: =cut
                   7455: 
1.200     albertel 7456: sub scantron_remove_file {
1.192     albertel 7457:     my ($which)=@_;
1.257     albertel 7458:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7459:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7460:     my $file='scantron_';
1.200     albertel 7461:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7462: 	$file.=$which.'_';
1.192     albertel 7463:     } else {
                   7464: 	return 'refused';
                   7465:     }
1.257     albertel 7466:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7467:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7468: }
                   7469: 
1.423     albertel 7470: 
                   7471: =pod
                   7472: 
                   7473: =item scantron_remove_scan_data
                   7474: 
1.596.2.6  raeburn  7475:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7476:    data file.  (In the case that both the are doing skipped records we need
                   7477:    to remember the old skipped lines for the time being so that element
                   7478:    persists for a while.)
                   7479: 
1.423     albertel 7480: =cut
                   7481: 
1.200     albertel 7482: sub scantron_remove_scan_data {
1.257     albertel 7483:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7484:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7485:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7486:     my @todelete;
1.257     albertel 7487:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7488:     foreach my $key (@keys) {
                   7489: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7490: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7491: 		$key=~/remember_skipping/) {
                   7492: 		next;
                   7493: 	    }
1.192     albertel 7494: 	    push(@todelete,$key);
                   7495: 	}
                   7496:     }
1.200     albertel 7497:     my $result;
1.192     albertel 7498:     if (@todelete) {
1.491     albertel 7499: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7500: 				       \@todelete,$cdom,$cname);
                   7501:     } else {
                   7502: 	$result = 'ok';
1.192     albertel 7503:     }
                   7504:     return $result;
                   7505: }
                   7506: 
1.423     albertel 7507: 
                   7508: =pod
                   7509: 
                   7510: =item scantron_getfile
                   7511: 
1.596.2.6  raeburn  7512:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7513:     the scan_data hash
                   7514:   
                   7515:   Arguments:
                   7516:     None
                   7517: 
                   7518:   Returns:
                   7519:     2 hash references
                   7520: 
                   7521:      - first one has 
                   7522:          orig      -
                   7523:          corrected -
                   7524:          skipped   -  each of which points to an array ref of the specified
                   7525:                       file broken up into individual lines
                   7526:          count     - number of scanlines
                   7527:  
                   7528:      - second is the scan_data hash possible keys are
1.425     albertel 7529:        ($number refers to scanline numbered $number and thus the key affects
                   7530:         only that scanline
                   7531:         $bubline refers to the specific bubble line element and the aspects
                   7532:         refers to that specific bubble line element)
                   7533: 
                   7534:        $number.user - username:domain to use
                   7535:        $number.CODE_ignore_dup 
                   7536:                     - ignore the duplicate CODE error 
                   7537:        $number.useCODE
                   7538:                     - use the CODE in the scanline as is
                   7539:        $number.no_bubble.$bubline
                   7540:                     - it is valid that there is no bubbled in bubble
                   7541:                       at $number $bubline
                   7542:        remember_skipping
                   7543:                     - a frozen hash containing keys of $number and values
                   7544:                       of either 
                   7545:                         1 - we are on a 'do skipped records pass' and plan
                   7546:                             on processing this line
                   7547:                         2 - we are on a 'do skipped records pass' and this
                   7548:                             scanline has been marked to skip yet again
1.424     albertel 7549: 
1.423     albertel 7550: =cut
                   7551: 
1.157     albertel 7552: sub scantron_getfile {
1.200     albertel 7553:     #FIXME really would prefer a scantron directory
1.257     albertel 7554:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7555:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7556:     my $lines;
                   7557:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7558: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7559:     my %scanlines;
                   7560:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7561:     my $temp=$scanlines{'orig'};
                   7562:     $scanlines{'count'}=$#$temp;
                   7563: 
                   7564:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7565: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7566:     if ($lines eq '-1') {
                   7567: 	$scanlines{'corrected'}=[];
                   7568:     } else {
                   7569: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7570:     }
                   7571:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7572: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7573:     if ($lines eq '-1') {
                   7574: 	$scanlines{'skipped'}=[];
                   7575:     } else {
                   7576: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7577:     }
1.175     albertel 7578:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7579:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7580:     my %scan_data = @tmp;
                   7581:     return (\%scanlines,\%scan_data);
                   7582: }
                   7583: 
1.423     albertel 7584: =pod
                   7585: 
                   7586: =item lonnet_putfile
                   7587: 
1.424     albertel 7588:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7589: 
                   7590:  Arguments:
                   7591:    $contents - data to store
                   7592:    $filename - filename to store $contents into
                   7593: 
                   7594:  Returns:
                   7595:    result value from &Apache::lonnet::finishuserfileupload
                   7596: 
1.423     albertel 7597: =cut
                   7598: 
1.157     albertel 7599: sub lonnet_putfile {
                   7600:     my ($contents,$filename)=@_;
1.257     albertel 7601:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7602:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7603:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7604:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7605: 
                   7606: }
                   7607: 
1.423     albertel 7608: =pod
                   7609: 
                   7610: =item scantron_putfile
                   7611: 
1.596.2.6  raeburn  7612:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7613:     scan_data hash. (Does not modify the original version only the
                   7614:     corrected and skipped versions.
                   7615: 
                   7616:  Arguments:
                   7617:     $scanlines - hash ref that looks like the first return value from
                   7618:                  &scantron_getfile()
                   7619:     $scan_data - hash ref that looks like the second return value from
                   7620:                  &scantron_getfile()
                   7621: 
1.423     albertel 7622: =cut
                   7623: 
1.157     albertel 7624: sub scantron_putfile {
                   7625:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7626:     #FIXME really would prefer a scantron directory
1.257     albertel 7627:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7628:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7629:     if ($scanlines) {
                   7630: 	my $prefix='scantron_';
1.157     albertel 7631: # no need to update orig, shouldn't change
                   7632: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7633: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7634: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7635: 			$prefix.'corrected_'.
1.257     albertel 7636: 			$env{'form.scantron_selectfile'});
1.200     albertel 7637: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7638: 			$prefix.'skipped_'.
1.257     albertel 7639: 			$env{'form.scantron_selectfile'});
1.200     albertel 7640:     }
1.175     albertel 7641:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7642: }
                   7643: 
1.423     albertel 7644: =pod
                   7645: 
                   7646: =item scantron_get_line
                   7647: 
1.424     albertel 7648:    Returns the correct version of the scanline
                   7649: 
                   7650:  Arguments:
                   7651:     $scanlines - hash ref that looks like the first return value from
                   7652:                  &scantron_getfile()
                   7653:     $scan_data - hash ref that looks like the second return value from
                   7654:                  &scantron_getfile()
                   7655:     $i         - number of the requested line (starts at 0)
                   7656: 
                   7657:  Returns:
                   7658:    A scanline, (either the original or the corrected one if it
                   7659:    exists), or undef if the requested scanline should be
                   7660:    skipped. (Either because it's an skipped scanline, or it's an
                   7661:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7662:    pass.
                   7663: 
1.423     albertel 7664: =cut
                   7665: 
1.157     albertel 7666: sub scantron_get_line {
1.200     albertel 7667:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7668:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7669:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7670:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7671:     return $scanlines->{'orig'}[$i]; 
                   7672: }
                   7673: 
1.423     albertel 7674: =pod
                   7675: 
                   7676: =item scantron_todo_count
                   7677: 
1.424     albertel 7678:     Counts the number of scanlines that need processing.
                   7679: 
                   7680:  Arguments:
                   7681:     $scanlines - hash ref that looks like the first return value from
                   7682:                  &scantron_getfile()
                   7683:     $scan_data - hash ref that looks like the second return value from
                   7684:                  &scantron_getfile()
                   7685: 
                   7686:  Returns:
                   7687:     $count - number of scanlines to process
                   7688: 
1.423     albertel 7689: =cut
                   7690: 
1.200     albertel 7691: sub get_todo_count {
                   7692:     my ($scanlines,$scan_data)=@_;
                   7693:     my $count=0;
                   7694:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7695: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7696: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7697: 	$count++;
                   7698:     }
                   7699:     return $count;
                   7700: }
                   7701: 
1.423     albertel 7702: =pod
                   7703: 
                   7704: =item scantron_put_line
                   7705: 
1.596.2.6  raeburn  7706:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7707:     data file.
                   7708: 
                   7709:  Arguments:
                   7710:     $scanlines - hash ref that looks like the first return value from
                   7711:                  &scantron_getfile()
                   7712:     $scan_data - hash ref that looks like the second return value from
                   7713:                  &scantron_getfile()
                   7714:     $i         - line number to update
                   7715:     $newline   - contents of the updated scanline
                   7716:     $skip      - if true make the line for skipping and update the
                   7717:                  'skipped' file
                   7718: 
1.423     albertel 7719: =cut
                   7720: 
1.157     albertel 7721: sub scantron_put_line {
1.200     albertel 7722:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7723:     if ($skip) {
                   7724: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7725: 	&start_skipping($scan_data,$i);
1.157     albertel 7726: 	return;
                   7727:     }
                   7728:     $scanlines->{'corrected'}[$i]=$newline;
                   7729: }
                   7730: 
1.423     albertel 7731: =pod
                   7732: 
                   7733: =item scantron_clear_skip
                   7734: 
1.424     albertel 7735:    Remove a line from the 'skipped' file
                   7736: 
                   7737:  Arguments:
                   7738:     $scanlines - hash ref that looks like the first return value from
                   7739:                  &scantron_getfile()
                   7740:     $scan_data - hash ref that looks like the second return value from
                   7741:                  &scantron_getfile()
                   7742:     $i         - line number to update
                   7743: 
1.423     albertel 7744: =cut
                   7745: 
1.376     albertel 7746: sub scantron_clear_skip {
                   7747:     my ($scanlines,$scan_data,$i)=@_;
                   7748:     if (exists($scanlines->{'skipped'}[$i])) {
                   7749: 	undef($scanlines->{'skipped'}[$i]);
                   7750: 	return 1;
                   7751:     }
                   7752:     return 0;
                   7753: }
                   7754: 
1.423     albertel 7755: =pod
                   7756: 
                   7757: =item scantron_filter_not_exam
                   7758: 
1.424     albertel 7759:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7760:    filter out resources that are not marked as 'exam' mode
                   7761: 
1.423     albertel 7762: =cut
                   7763: 
1.334     albertel 7764: sub scantron_filter_not_exam {
                   7765:     my ($curres)=@_;
                   7766:     
                   7767:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7768: 	# if the user has asked to not have either hidden
                   7769: 	# or 'randomout' controlled resources to be graded
                   7770: 	# don't include them
                   7771: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7772: 	    && $curres->randomout) {
                   7773: 	    return 0;
                   7774: 	}
                   7775: 	return 1;
                   7776:     }
                   7777:     return 0;
                   7778: }
                   7779: 
1.423     albertel 7780: =pod
                   7781: 
                   7782: =item scantron_validate_sequence
                   7783: 
1.424     albertel 7784:     Validates the selected sequence, checking for resource that are
                   7785:     not set to exam mode.
                   7786: 
1.423     albertel 7787: =cut
                   7788: 
1.334     albertel 7789: sub scantron_validate_sequence {
                   7790:     my ($r,$currentphase) = @_;
                   7791: 
                   7792:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7793:     unless (ref($navmap)) {
                   7794:         $r->print(&navmap_errormsg());
                   7795:         return (1,$currentphase);
                   7796:     }
1.334     albertel 7797:     my (undef,undef,$sequence)=
                   7798: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7799: 
                   7800:     my $map=$navmap->getResourceByUrl($sequence);
                   7801: 
                   7802:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7803:                                     value="ignore" />');
                   7804:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7805: 	my @resources=
                   7806: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7807: 	if (@resources) {
1.596.2.12.2.  0(raebur 7808:2): 	    $r->print('<p class="LC_warning">'
                   7809:2):                .&mt('Some resources in the sequence currently are not set to'
                   7810:2):                    .' exam mode. Grading these resources currently may not'
                   7811:2):                    .' work correctly.')
                   7812:2):                .'</p>'
                   7813:2):             );
1.334     albertel 7814: 	    return (1,$currentphase);
                   7815: 	}
                   7816:     }
                   7817: 
                   7818:     return (0,$currentphase+1);
                   7819: }
                   7820: 
1.423     albertel 7821: 
                   7822: 
1.157     albertel 7823: sub scantron_validate_ID {
                   7824:     my ($r,$currentphase) = @_;
                   7825:     
                   7826:     #get student info
                   7827:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7828:     my %idmap=&username_to_idmap($classlist);
                   7829: 
                   7830:     #get scantron line setup
1.596.2.12.2.  9(raebur 7831:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7832:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7833: 
                   7834:     my $nav_error;
1.596.2.12.2.  (raeburn 7835:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7836:     if ($nav_error) {
                   7837:         $r->print(&navmap_errormsg());
                   7838:         return(1,$currentphase);
                   7839:     }
1.157     albertel 7840: 
                   7841:     my %found=('ids'=>{},'usernames'=>{});
                   7842:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7843: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7844: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7845: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7846: 						 $scan_data);
                   7847: 	my $id=$$scan_record{'scantron.ID'};
                   7848: 	my $found;
                   7849: 	foreach my $checkid (keys(%idmap)) {
                   7850: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7851: 	}
                   7852: 	if ($found) {
                   7853: 	    my $username=$idmap{$found};
                   7854: 	    if ($found{'ids'}{$found}) {
                   7855: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7856: 					 $line,'duplicateID',$found);
1.194     albertel 7857: 		return(1,$currentphase);
1.157     albertel 7858: 	    } elsif ($found{'usernames'}{$username}) {
                   7859: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7860: 					 $line,'duplicateID',$username);
1.194     albertel 7861: 		return(1,$currentphase);
1.157     albertel 7862: 	    }
1.186     albertel 7863: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7864: 	    $found{'ids'}{$found}++;
                   7865: 	    $found{'usernames'}{$username}++;
                   7866: 	} else {
                   7867: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7868: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7869: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7870: 		    &scantron_get_correction($r,$i,$scan_record,
                   7871: 					     \%scantron_config,
                   7872: 					     $line,'duplicateID',$username);
1.194     albertel 7873: 		    return(1,$currentphase);
1.157     albertel 7874: 		} elsif (!defined($username)) {
                   7875: 		    &scantron_get_correction($r,$i,$scan_record,
                   7876: 					     \%scantron_config,
                   7877: 					     $line,'incorrectID');
1.194     albertel 7878: 		    return(1,$currentphase);
1.157     albertel 7879: 		}
                   7880: 		$found{'usernames'}{$username}++;
                   7881: 	    } else {
                   7882: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7883: 					 $line,'incorrectID');
1.194     albertel 7884: 		return(1,$currentphase);
1.157     albertel 7885: 	    }
                   7886: 	}
                   7887:     }
                   7888: 
                   7889:     return (0,$currentphase+1);
                   7890: }
                   7891: 
1.423     albertel 7892: 
1.157     albertel 7893: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7894:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7895:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7896: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7897: #to show both the current line and the previous one and allow skipping
                   7898: #the previous one or the current one
                   7899: 
1.333     albertel 7900:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7901:         $r->print(
                   7902:             '<p class="LC_warning">'
                   7903:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7904:                 "<b>$error</b>",
                   7905:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7906:            ."</p> \n");
1.157     albertel 7907:     } else {
1.596.2.6  raeburn  7908:         $r->print(
                   7909:             '<p class="LC_warning">'
                   7910:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7911:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7912:            ."</p> \n");
                   7913:     }
                   7914:     my $message =
                   7915:         '<p>'
                   7916:        .&mt('The ID on the form is [_1]',
                   7917:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7918:        .'<br />'
1.596.2.12  raeburn  7919:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7920:             $$scan_record{'scantron.LastName'},
                   7921:             $$scan_record{'scantron.FirstName'})
                   7922:        .'</p>';
1.242     albertel 7923: 
1.157     albertel 7924:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7925:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7926:                            # Array populated for doublebubble or
                   7927:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7928:                            # to validate radio button checking   
                   7929: 
1.157     albertel 7930:     if ($error =~ /ID$/) {
1.186     albertel 7931: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7932: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7933: 		      "</p>\n");
1.157     albertel 7934: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7935: 	    $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 7936: 	}
1.242     albertel 7937: 	$r->print($message);
1.492     albertel 7938: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7939: 	$r->print("\n<ul><li> ");
                   7940: 	#FIXME it would be nice if this sent back the user ID and
                   7941: 	#could do partial userID matches
                   7942: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7943: 				       'scantron_username','scantron_domain'));
                   7944: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7945:3): 	$r->print("\n:\n".
1.257     albertel 7946: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7947: 
                   7948: 	$r->print('</li>');
1.186     albertel 7949:     } elsif ($error =~ /CODE$/) {
                   7950: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7951: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7952: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7953: 	    $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 7954: 	}
1.596.2.6  raeburn  7955:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7956:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7957:                  ."</p>\n");
1.242     albertel 7958: 	$r->print($message);
1.596.2.6  raeburn  7959: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7960: 	$r->print("\n<br /> ");
1.194     albertel 7961: 	my $i=0;
1.273     albertel 7962: 	if ($error eq 'incorrectCODE' 
                   7963: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7964: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7965: 	    if ($closest > 0) {
                   7966: 		foreach my $testcode (@{$closest}) {
                   7967: 		    my $checked='';
1.569     bisitz   7968: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7969: 		    $r->print("
                   7970:    <label>
1.569     bisitz   7971:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7972:        ".&mt("Use the similar CODE [_1] instead.",
                   7973: 	    "<b><tt>".$testcode."</tt></b>")."
                   7974:     </label>
                   7975:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7976: 		    $r->print("\n<br />");
                   7977: 		    $i++;
                   7978: 		}
1.194     albertel 7979: 	    }
                   7980: 	}
1.273     albertel 7981: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7982: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7983: 	    $r->print("
                   7984:     <label>
1.569     bisitz   7985:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7986:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7987: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7988:     </label>");
1.273     albertel 7989: 	    $r->print("\n<br />");
                   7990: 	}
1.194     albertel 7991: 
1.596.2.12.2.  1(raebur 7992:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7993: function change_radio(field) {
1.190     albertel 7994:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7995:     var i;
                   7996:     for (i=0;i<slct.length;i++) {
                   7997:         if (slct[i].value==field) { slct[i].checked=true; }
                   7998:     }
                   7999: }
                   8000: ENDSCRIPT
1.187     albertel 8001: 	my $href="/adm/pickcode?".
1.359     www      8002: 	   "form=".&escape("scantronupload").
                   8003: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8004: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8005: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8006: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8007: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8008: 	    $r->print("
                   8009:     <label>
                   8010:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8011:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8012: 	     "<a target='_blank' href='$href'>","</a>")."
                   8013:     </label> 
1.558     bisitz   8014:     ".&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 8015: 	    $r->print("\n<br />");
                   8016: 	}
1.492     albertel 8017: 	$r->print("
                   8018:     <label>
                   8019:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8020:        ".&mt("Use [_1] as the CODE.",
                   8021: 	     "</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 8022: 	$r->print("\n<br /><br />");
1.157     albertel 8023:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  8024: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8025: 
                   8026: 	# The form field scantron_questions is acutally a list of line numbers.
                   8027: 	# represented by this form so:
                   8028: 
1.596.2.12.2.  6(raebur 8029:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8030:3):                                                 $respnumlookup,$startline);
1.497     foxr     8031: 
1.157     albertel 8032: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8033: 		  $line_list.'" />');
1.242     albertel 8034: 	$r->print($message);
1.492     albertel 8035: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8036: 	foreach my $question (@{$arg}) {
1.503     raeburn  8037: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8038:3):                                                    $scan_record, $error,
                   8039:3):                                                    $randomorder,$randompick,
                   8040:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8041:             push(@lines_to_correct,@linenums);
1.157     albertel 8042: 	}
1.503     raeburn  8043:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8044:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  8045: 	$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 8046: 	$r->print($message);
1.492     albertel 8047: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8048: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8049: 
1.503     raeburn  8050: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8051: 	# a list of question numbers. Therefore:
                   8052: 	#
                   8053: 	
1.596.2.12.2.  6(raebur 8054:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8055:3):                                                 $respnumlookup,$startline);
1.497     foxr     8056: 
1.157     albertel 8057: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8058: 		  $line_list.'" />');
1.157     albertel 8059: 	foreach my $question (@{$arg}) {
1.503     raeburn  8060: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8061:3):                                                    $scan_record, $error,
                   8062:3):                                                    $randomorder,$randompick,
                   8063:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8064:             push(@lines_to_correct,@linenums);
1.157     albertel 8065: 	}
1.503     raeburn  8066:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8067:     } else {
                   8068: 	$r->print("\n<ul>");
                   8069:     }
                   8070:     $r->print("\n</li></ul>");
1.497     foxr     8071: }
                   8072: 
1.503     raeburn  8073: sub verify_bubbles_checked {
                   8074:     my (@ansnums) = @_;
                   8075:     my $ansnumstr = join('","',@ansnums);
                   8076:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.596.2.12.2.  6(raebur 8077:6):     &js_escape(\$warning);
          1(raebur 8078:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8079: function verify_bubble_radio(form) {
                   8080:     var ansnumArray = new Array ("$ansnumstr");
                   8081:     var need_bubble_count = 0;
                   8082:     for (var i=0; i<ansnumArray.length; i++) {
                   8083:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8084:             var bubble_picked = 0; 
                   8085:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8086:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8087:                     bubble_picked = 1;
                   8088:                 }
                   8089:             }
                   8090:             if (bubble_picked == 0) {
                   8091:                 need_bubble_count ++;
                   8092:             }
                   8093:         }
                   8094:     }
                   8095:     if (need_bubble_count) {
                   8096:         alert("$warning");
                   8097:         return;
                   8098:     }
                   8099:     form.submit(); 
                   8100: }
                   8101: ENDSCRIPT
                   8102:     return $output;
                   8103: }
                   8104: 
1.497     foxr     8105: =pod
                   8106: 
                   8107: =item  questions_to_line_list
1.157     albertel 8108: 
1.497     foxr     8109: Converts a list of questions into a string of comma separated
                   8110: line numbers in the answer sheet used by the questions.  This is
                   8111: used to fill in the scantron_questions form field.
                   8112: 
                   8113:   Arguments:
                   8114:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8115:3):      randomorder  - True if randomorder in use.
                   8116:3):      randompick   - True if randompick in use.
                   8117:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8118:3):                      for current line to question number used for same question
                   8119:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8120:3):      startline    - Reference to hash where key is question number (0 is first)
                   8121:3):                     and key is number of first bubble line for current student
                   8122:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8123: 
                   8124: =cut
                   8125: 
                   8126: 
                   8127: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8128:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8129:     my @lines;
                   8130: 
1.503     raeburn  8131:     foreach my $item (@{$questions}) {
                   8132:         my $question = $item;
                   8133:         my ($first,$count,$last);
                   8134:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8135:             $question = $1;
                   8136:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8137:3):             my $responsenum = $question-1;
                   8138:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8139:3):                 $responsenum = $respnumlookup->{$question-1};
                   8140:3):                 if (ref($startline) eq 'HASH') {
                   8141:3):                     $first = $startline->{$question-1} + 1;
                   8142:3):                 }
                   8143:3):             } else {
                   8144:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8145:3):             }
          7(raebur 8146:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8147:             my $subcount = 1;
                   8148:             while ($subcount<$subquestion) {
                   8149:                 $first += $subans[$subcount-1];
                   8150:                 $subcount ++;
                   8151:             }
                   8152:             $count = $subans[$subquestion-1];
                   8153:         } else {
1.596.2.12.2.  7(raebur 8154:3):             my $responsenum = $question-1;
                   8155:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8156:3):                 $responsenum = $respnumlookup->{$question-1};
                   8157:3):                 if (ref($startline) eq 'HASH') {
                   8158:3):                     $first = $startline->{$question-1} + 1;
                   8159:3):                 }
                   8160:3):             } else {
                   8161:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8162:3):             }
                   8163:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8164:         }
1.506     raeburn  8165:         $last = $first+$count-1;
1.503     raeburn  8166:         push(@lines, ($first..$last));
1.497     foxr     8167:     }
                   8168:     return join(',', @lines);
                   8169: }
                   8170: 
                   8171: =pod 
                   8172: 
                   8173: =item prompt_for_corrections
                   8174: 
                   8175: Prompts for a potentially multiline correction to the
                   8176: user's bubbling (factors out common code from scantron_get_correction
                   8177: for multi and missing bubble cases).
                   8178: 
                   8179:  Arguments:
                   8180:    $r           - Apache request object.
                   8181:    $question    - The question number to prompt for.
                   8182:    $scan_config - The scantron file configuration hash.
                   8183:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8184:    $error       - Type of error
1.596.2.12.2.  7(raebur 8185:3):    $randomorder - True if randomorder in use.
                   8186:3):    $randompick  - True if randompick in use.
                   8187:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8188:3):                     for current line to question number used for same question
                   8189:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8190:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8191:3):                   and value is number of first bubble line for current student
                   8192:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8193: 
                   8194:  Implicit inputs:
                   8195:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8196:                                   Numbered from 0 (but question numbers are from
                   8197:                                   1.
                   8198:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8199:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8200:                                   type problems render as separate sub-questions, 
1.503     raeburn  8201:                                   in exam mode. This hash contains a 
                   8202:                                   comma-separated list of the lines per 
                   8203:                                   sub-question.
1.510     raeburn  8204:    %responsetype_per_response   - essayresponse, formularesponse,
                   8205:                                   stringresponse, imageresponse, reactionresponse,
                   8206:                                   and organicresponse type problem parts can have
1.503     raeburn  8207:                                   multiple lines per response if the weight
                   8208:                                   assigned exceeds 10.  In this case, only
                   8209:                                   one bubble per line is permitted, but more 
                   8210:                                   than one line might contain bubbles, e.g.
                   8211:                                   bubbling of: line 1 - J, line 2 - J, 
                   8212:                                   line 3 - B would assign 22 points.  
1.497     foxr     8213: 
                   8214: =cut
                   8215: 
                   8216: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8217:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8218:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8219:     my ($current_line,$lines);
                   8220:     my @linenums;
                   8221:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8222:3):     my ($first,$responsenum);
1.503     raeburn  8223:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8224:         $question = $1;
                   8225:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8226:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8227:3):             $responsenum = $respnumlookup->{$question-1};
                   8228:3):             if (ref($startline) eq 'HASH') {
                   8229:3):                 $first = $startline->{$question-1};
                   8230:3):             }
                   8231:3):         } else {
                   8232:3):             $responsenum = $question-1;
          7(raebur 8233:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8234:3):         }
                   8235:3):         $current_line = $first + 1 ;
                   8236:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8237:         my $subcount = 1;
                   8238:         while ($subcount<$subquestion) {
                   8239:             $current_line += $subans[$subcount-1];
                   8240:             $subcount ++;
                   8241:         }
                   8242:         $lines = $subans[$subquestion-1];
                   8243:     } else {
1.596.2.12.2.  6(raebur 8244:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8245:3):             $responsenum = $respnumlookup->{$question-1};
                   8246:3):             if (ref($startline) eq 'HASH') {
                   8247:3):                 $first = $startline->{$question-1};
                   8248:3):             }
                   8249:3):         } else {
                   8250:3):             $responsenum = $question-1;
                   8251:3):             $first = $first_bubble_line{$responsenum};
                   8252:3):         }
                   8253:3):         $current_line = $first + 1;
                   8254:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8255:     }
1.497     foxr     8256:     if ($lines > 1) {
1.503     raeburn  8257:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8258:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8259:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8260:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8261:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8262:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8263:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8264:3):             $r->print(&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).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&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.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  8265:         } else {
                   8266:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8267:         }
1.497     foxr     8268:     }
                   8269:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8270:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8271:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8272: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8273:         push(@linenums,$current_line);
1.497     foxr     8274: 	$current_line++;
                   8275:     }
                   8276:     if ($lines > 1) {
                   8277: 	$r->print("<hr /><br />");
                   8278:     }
1.503     raeburn  8279:     return @linenums;
1.157     albertel 8280: }
1.423     albertel 8281: 
                   8282: =pod
                   8283: 
                   8284: =item scantron_bubble_selector
                   8285:   
                   8286:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8287:    possibly showing the existing the selected bubbles if known
1.423     albertel 8288: 
                   8289:  Arguments:
                   8290:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8291:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8292:     $line        - Number of the line being displayed.
1.503     raeburn  8293:     $questionnum - Question number (may include subquestion)
                   8294:     $error       - Type of error.
1.497     foxr     8295:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8296: 
                   8297: =cut
                   8298: 
1.157     albertel 8299: sub scantron_bubble_selector {
1.503     raeburn  8300:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8301:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8302: 
                   8303:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8304:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8305:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8306:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8307:):             $max=$$scan_config{'BubblesPerRow'};
                   8308:):             if (($scmode eq 'number') && ($max > 10)) {
                   8309:):                 $max = 10;
                   8310:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8311:):                 $max = 26;
                   8312:):             }
                   8313:):         } else {
                   8314:):             $max = 10;
                   8315:):         }
                   8316:):     }
1.274     albertel 8317: 
1.157     albertel 8318:     my @alphabet=('A'..'Z');
1.503     raeburn  8319:     $r->print(&Apache::loncommon::start_data_table().
                   8320:               &Apache::loncommon::start_data_table_row());
                   8321:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8322:     for (my $i=0;$i<$max+1;$i++) {
                   8323: 	$r->print("\n".'<td align="center">');
                   8324: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8325: 	else { $r->print('&nbsp;'); }
                   8326: 	$r->print('</td>');
                   8327:     }
1.503     raeburn  8328:     $r->print(&Apache::loncommon::end_data_table_row().
                   8329:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8330:     for (my $i=0;$i<$max;$i++) {
                   8331: 	$r->print("\n".
                   8332: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8333: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8334:     }
1.503     raeburn  8335:     my $nobub_checked = ' ';
                   8336:     if ($error eq 'missingbubble') {
                   8337:         $nobub_checked = ' checked = "checked" ';
                   8338:     }
                   8339:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8340: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8341:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8342:               $line.'" value="'.$questionnum.'" /></td>');
                   8343:     $r->print(&Apache::loncommon::end_data_table_row().
                   8344:               &Apache::loncommon::end_data_table());
1.157     albertel 8345: }
                   8346: 
1.423     albertel 8347: =pod
                   8348: 
                   8349: =item num_matches
                   8350: 
1.424     albertel 8351:    Counts the number of characters that are the same between the two arguments.
                   8352: 
                   8353:  Arguments:
                   8354:    $orig - CODE from the scanline
                   8355:    $code - CODE to match against
                   8356: 
                   8357:  Returns:
                   8358:    $count - integer count of the number of same characters between the
                   8359:             two arguments
                   8360: 
1.423     albertel 8361: =cut
                   8362: 
1.194     albertel 8363: sub num_matches {
                   8364:     my ($orig,$code) = @_;
                   8365:     my @code=split(//,$code);
                   8366:     my @orig=split(//,$orig);
                   8367:     my $same=0;
                   8368:     for (my $i=0;$i<scalar(@code);$i++) {
                   8369: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8370:     }
                   8371:     return $same;
                   8372: }
                   8373: 
1.423     albertel 8374: =pod
                   8375: 
                   8376: =item scantron_get_closely_matching_CODEs
                   8377: 
1.424     albertel 8378:    Cycles through all CODEs and finds the set that has the greatest
                   8379:    number of same characters as the provided CODE
                   8380: 
                   8381:  Arguments:
                   8382:    $allcodes - hash ref returned by &get_codes()
                   8383:    $CODE     - CODE from the current scanline
                   8384: 
                   8385:  Returns:
                   8386:    2 element list
                   8387:     - first elements is number of how closely matching the best fit is 
                   8388:       (5 means best set has 5 matching characters)
                   8389:     - second element is an arrary ref containing the set of valid CODEs
                   8390:       that best fit the passed in CODE
                   8391: 
1.423     albertel 8392: =cut
                   8393: 
1.194     albertel 8394: sub scantron_get_closely_matching_CODEs {
                   8395:     my ($allcodes,$CODE)=@_;
                   8396:     my @CODEs;
                   8397:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8398: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8399:     }
                   8400: 
                   8401:     return ($#CODEs,$CODEs[-1]);
                   8402: }
                   8403: 
1.423     albertel 8404: =pod
                   8405: 
                   8406: =item get_codes
                   8407: 
1.424     albertel 8408:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8409:    set of remembered CODEs.
                   8410: 
                   8411:  Arguments:
                   8412:   $old_name - name of the set of remembered CODEs
                   8413:   $cdom     - domain of the course
                   8414:   $cnum     - internal course name
                   8415: 
                   8416:  Returns:
                   8417:   %allcodes - keys are the valid CODEs, values are all 1
                   8418: 
1.423     albertel 8419: =cut
                   8420: 
1.194     albertel 8421: sub get_codes {
1.280     foxr     8422:     my ($old_name, $cdom, $cnum) = @_;
                   8423:     if (!$old_name) {
                   8424: 	$old_name=$env{'form.scantron_CODElist'};
                   8425:     }
                   8426:     if (!$cdom) {
                   8427: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8428:     }
                   8429:     if (!$cnum) {
                   8430: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8431:     }
1.278     albertel 8432:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8433: 				    $cdom,$cnum);
                   8434:     my %allcodes;
                   8435:     if ($result{"type\0$old_name"} eq 'number') {
                   8436: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8437:     } else {
                   8438: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8439:     }
1.194     albertel 8440:     return %allcodes;
                   8441: }
                   8442: 
1.423     albertel 8443: =pod
                   8444: 
                   8445: =item scantron_validate_CODE
                   8446: 
1.424     albertel 8447:    Validates all scanlines in the selected file to not have any
                   8448:    invalid or underspecified CODEs and that none of the codes are
                   8449:    duplicated if this was requested.
                   8450: 
1.423     albertel 8451: =cut
                   8452: 
1.157     albertel 8453: sub scantron_validate_CODE {
                   8454:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8455:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8456:     if ($scantron_config{'CODElocation'} &&
                   8457: 	$scantron_config{'CODEstart'} &&
                   8458: 	$scantron_config{'CODElength'}) {
1.257     albertel 8459: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8460: 	    &FIXME_blow_up()
                   8461: 	}
                   8462:     } else {
                   8463: 	return (0,$currentphase+1);
                   8464:     }
                   8465:     
                   8466:     my %usedCODEs;
                   8467: 
1.194     albertel 8468:     my %allcodes=&get_codes();
1.186     albertel 8469: 
1.582     raeburn  8470:     my $nav_error;
1.596.2.12.2.  (raeburn 8471:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8472:     if ($nav_error) {
                   8473:         $r->print(&navmap_errormsg());
                   8474:         return(1,$currentphase);
                   8475:     }
1.447     foxr     8476: 
1.186     albertel 8477:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8478:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8479: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8480: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8481: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8482: 						 $scan_data);
                   8483: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8484: 	my $error=0;
1.224     albertel 8485: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8486: 	    &scantron_get_correction($r,$i,$scan_record,
                   8487: 				     \%scantron_config,
                   8488: 				     $line,'incorrectCODE',\%allcodes);
                   8489: 	    return(1,$currentphase);
                   8490: 	}
1.221     albertel 8491: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8492: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8493: 	    &scantron_get_correction($r,$i,$scan_record,
                   8494: 				     \%scantron_config,
1.194     albertel 8495: 				     $line,'incorrectCODE',\%allcodes);
                   8496: 	    return(1,$currentphase);
1.186     albertel 8497: 	}
1.214     albertel 8498: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8499: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8500: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8501: 	    &scantron_get_correction($r,$i,$scan_record,
                   8502: 				     \%scantron_config,
1.194     albertel 8503: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8504: 	    return(1,$currentphase);
1.186     albertel 8505: 	}
1.524     raeburn  8506: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8507:     }
1.157     albertel 8508:     return (0,$currentphase+1);
                   8509: }
                   8510: 
1.423     albertel 8511: =pod
                   8512: 
                   8513: =item scantron_validate_doublebubble
                   8514: 
1.424     albertel 8515:    Validates all scanlines in the selected file to not have any
                   8516:    bubble lines with multiple bubbles marked.
                   8517: 
1.423     albertel 8518: =cut
                   8519: 
1.157     albertel 8520: sub scantron_validate_doublebubble {
                   8521:     my ($r,$currentphase) = @_;
                   8522:     #get student info
                   8523:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8524:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8525:3):     my (undef,undef,$sequence)=
                   8526:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8527: 
                   8528:     #get scantron line setup
1.596.2.12.2.  9(raebur 8529:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8530:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8531:3): 
                   8532:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8533:3):     unless (ref($navmap)) {
                   8534:3):         $r->print(&navmap_errormsg());
                   8535:3):         return(1,$currentphase);
                   8536:3):     }
                   8537:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8538:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8539:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8540:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8541:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8542:3): 
1.583     raeburn  8543:     my $nav_error;
1.596.2.12.2.  6(raebur 8544:3):     if (ref($map)) {
                   8545:3):         $randomorder = $map->randomorder();
                   8546:3):         $randompick = $map->randompick();
          0(raebur 8547:2):         unless ($randomorder || $randompick) {
                   8548:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8549:2):                 if ($res->randomorder()) {
                   8550:2):                     $randomorder = 1;
                   8551:2):                 }
                   8552:2):                 if ($res->randompick()) {
                   8553:2):                     $randompick = 1;
                   8554:2):                 }
                   8555:2):                 last if ($randomorder || $randompick);
                   8556:2):             }
                   8557:2):         }
          6(raebur 8558:3):         if ($randomorder || $randompick) {
                   8559:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8560:3):             if ($nav_error) {
                   8561:3):                 $r->print(&navmap_errormsg());
                   8562:3):                 return(1,$currentphase);
                   8563:3):             }
                   8564:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8565:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8566:3):         }
                   8567:3):     } else {
                   8568:3):         $r->print(&navmap_errormsg());
                   8569:3):         return(1,$currentphase);
                   8570:3):     }
                   8571:3): 
          (raeburn 8572:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8573:     if ($nav_error) {
                   8574:         $r->print(&navmap_errormsg());
                   8575:         return(1,$currentphase);
                   8576:     }
1.447     foxr     8577: 
1.157     albertel 8578:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8579: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8580: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8581: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8582:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8583:3):                                                  $randompick,$sequence,\@master_seq,
                   8584:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8585:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8586: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8587: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8588: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8589:3): 				 $$scan_record{'scantron.doubleerror'},
                   8590:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8591:     	return (1,$currentphase);
                   8592:     }
                   8593:     return (0,$currentphase+1);
                   8594: }
                   8595: 
1.423     albertel 8596: 
1.503     raeburn  8597: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8598:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8599:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8600: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8601: 	&restore_bubble_lines();
1.257     albertel 8602: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8603:     }
1.330     albertel 8604: 
1.447     foxr     8605:     my (undef, undef, $sequence) =
1.257     albertel 8606: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8607: 
1.447     foxr     8608:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8609:     unless (ref($navmap)) {
                   8610:         if (ref($nav_error)) {
                   8611:             $$nav_error = 1;
                   8612:         }
1.591     raeburn  8613:         return;
1.582     raeburn  8614:     }
1.191     albertel 8615:     my $map=$navmap->getResourceByUrl($sequence);
                   8616:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8617:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8618: 
                   8619:     &Apache::lonxml::clear_problem_counter();
                   8620: 
1.557     raeburn  8621:     my $uname       = $env{'user.name'};
                   8622:     my $udom        = $env{'user.domain'};
1.435     foxr     8623:     my $cid         = $env{'request.course.id'};
                   8624:     my $total_lines = 0;
                   8625:     %bubble_lines_per_response = ();
1.447     foxr     8626:     %first_bubble_line         = ();
1.503     raeburn  8627:     %subdivided_bubble_lines   = ();
                   8628:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8629:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8630: 
1.447     foxr     8631:     my $response_number = 0;
                   8632:     my $bubble_line     = 0;
1.191     albertel 8633:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8634:3):         my $resid = $resource->id();
          (raeburn 8635:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8636:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8637:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8638: 	    foreach my $part_id (@{$parts}) {
                   8639:                 my $lines;
                   8640: 
                   8641: 	        # TODO - make this a persistent hash not an array.
                   8642: 
                   8643:                 # optionresponse, matchresponse and rankresponse type items 
                   8644:                 # render as separate sub-questions in exam mode.
                   8645:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8646:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8647:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8648:                     my ($numbub,$numshown);
                   8649:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8650:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8651:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8652:                         }
                   8653:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8654:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8655:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8656:                         }
                   8657:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8658:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8659:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8660:                         }
                   8661:                     }
                   8662:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8663:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8664:                     }
1.596.2.12.2.  (raeburn 8665:):                     my $bubbles_per_row =
                   8666:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8667:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8668:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8669:                         $inner_bubble_lines++;
                   8670:                     }
                   8671:                     for (my $i=0; $i<$numshown; $i++) {
                   8672:                         $subdivided_bubble_lines{$response_number} .= 
                   8673:                             $inner_bubble_lines.',';
                   8674:                     }
                   8675:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8676:                     $lines = $numshown * $inner_bubble_lines;
                   8677:                 } else {
                   8678:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8679:):                 }
1.542     raeburn  8680: 
                   8681:                 $first_bubble_line{$response_number} = $bubble_line;
                   8682: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8683:                 $responsetype_per_response{$response_number} = 
                   8684:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8685:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8686: 	        $response_number++;
                   8687: 
                   8688: 	        $bubble_line +=  $lines;
                   8689: 	        $total_lines +=  $lines;
                   8690: 	    }
                   8691:         }
                   8692:     }
1.552     raeburn  8693:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8694: 
                   8695:     &save_bubble_lines();
                   8696:     $env{'form.scantron_maxbubble'} =
                   8697: 	$total_lines;
                   8698:     return $env{'form.scantron_maxbubble'};
                   8699: }
1.523     raeburn  8700: 
1.596.2.12.2.  (raeburn 8701:): sub bubblesheet_bubbles_per_row {
                   8702:):     my ($scantron_config) = @_;
                   8703:):     my $bubbles_per_row;
                   8704:):     if (ref($scantron_config) eq 'HASH') {
                   8705:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8706:):     }
                   8707:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8708:):         $bubbles_per_row = 10;
                   8709:):     }
                   8710:):     return $bubbles_per_row;
                   8711:): }
                   8712:): 
1.157     albertel 8713: sub scantron_validate_missingbubbles {
                   8714:     my ($r,$currentphase) = @_;
                   8715:     #get student info
                   8716:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8717:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8718:3):     my (undef,undef,$sequence)=
                   8719:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8720: 
                   8721:     #get scantron line setup
1.596.2.12.2.  9(raebur 8722:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8723:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8724:3): 
                   8725:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8726:3):     unless (ref($navmap)) {
                   8727:3):         $r->print(&navmap_errormsg());
                   8728:3):         return(1,$currentphase);
                   8729:3):     }
                   8730:3): 
                   8731:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8732:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8733:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8734:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8735:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8736:3): 
1.582     raeburn  8737:     my $nav_error;
1.596.2.12.2.  6(raebur 8738:3):     if (ref($map)) {
                   8739:3):         $randomorder = $map->randomorder();
                   8740:3):         $randompick = $map->randompick();
          0(raebur 8741:2):         unless ($randomorder || $randompick) {
                   8742:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8743:2):                 if ($res->randomorder()) {
                   8744:2):                     $randomorder = 1;
                   8745:2):                 }
                   8746:2):                 if ($res->randompick()) {
                   8747:2):                     $randompick = 1;
                   8748:2):                 }
                   8749:2):                 last if ($randomorder || $randompick);
                   8750:2):             }
                   8751:2):         }
          7(raebur 8752:3):         if ($randomorder || $randompick) {
                   8753:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8754:3):             if ($nav_error) {
                   8755:3):                 $r->print(&navmap_errormsg());
                   8756:3):                 return(1,$currentphase);
                   8757:3):             }
                   8758:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8759:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8760:3):         }
          6(raebur 8761:3):     } else {
                   8762:3):         $r->print(&navmap_errormsg());
          7(raebur 8763:3):         return(1,$currentphase);
          6(raebur 8764:3):     }
                   8765:3): 
                   8766:3): 
          (raeburn 8767:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8768:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8769:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8770:         return(1,$currentphase);
                   8771:     }
1.596.2.12.2.  6(raebur 8772:3): 
1.157     albertel 8773:     if (!$max_bubble) { $max_bubble=2**31; }
                   8774:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8775: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8776: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8777:3):         my $scan_record =
                   8778:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8779:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8780:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8781:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8782: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8783: 	my @to_correct;
1.470     foxr     8784: 	
                   8785: 	# Probably here's where the error is...
                   8786: 
1.157     albertel 8787: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8788:             my $lastbubble;
                   8789:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8790:3):                 my $question = $1;
                   8791:3):                 my $subquestion = $2;
                   8792:3):                 my ($first,$responsenum);
                   8793:3):                 if ($randomorder || $randompick) {
                   8794:3):                     $responsenum = $respnumlookup{$question-1};
                   8795:3):                     $first = $startline{$question-1};
                   8796:3):                 } else {
                   8797:3):                     $responsenum = $question-1;
                   8798:3):                     $first = $first_bubble_line{$responsenum};
                   8799:3):                 }
                   8800:3):                 if (!defined($first)) { next; }
          7(raebur 8801:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8802:3):                 my $subcount = 1;
                   8803:3):                 while ($subcount<$subquestion) {
                   8804:3):                     $first += $subans[$subcount-1];
                   8805:3):                     $subcount ++;
                   8806:3):                 }
                   8807:3):                 my $count = $subans[$subquestion-1];
                   8808:3):                 $lastbubble = $first + $count;
1.505     raeburn  8809:             } else {
1.596.2.12.2.  6(raebur 8810:3):                 my ($first,$responsenum);
                   8811:3):                 if ($randomorder || $randompick) {
                   8812:3):                     $responsenum = $respnumlookup{$missing-1};
                   8813:3):                     $first = $startline{$missing-1};
                   8814:3):                 } else {
                   8815:3):                     $responsenum = $missing-1;
                   8816:3):                     $first = $first_bubble_line{$responsenum};
                   8817:3):                 }
                   8818:3):                 if (!defined($first)) { next; }
                   8819:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8820:             }
                   8821:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8822: 	    push(@to_correct,$missing);
                   8823: 	}
                   8824: 	if (@to_correct) {
                   8825: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8826:3): 				     $line,'missingbubble',\@to_correct,
                   8827:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8828:3):                                      \%startline);
1.157     albertel 8829: 	    return (1,$currentphase);
                   8830: 	}
                   8831: 
                   8832:     }
                   8833:     return (0,$currentphase+1);
                   8834: }
                   8835: 
1.596.2.12.2.  (raeburn 8836:): sub hand_bubble_option {
                   8837:):     my (undef, undef, $sequence) =
                   8838:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8839:):     return if ($sequence eq '');
                   8840:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8841:):     unless (ref($navmap)) {
                   8842:):         return;
                   8843:):     }
                   8844:):     my $needs_hand_bubbles;
                   8845:):     my $map=$navmap->getResourceByUrl($sequence);
                   8846:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8847:):     foreach my $res (@resources) {
                   8848:):         if (ref($res)) {
                   8849:):             if ($res->is_problem()) {
                   8850:):                 my $partlist = $res->parts();
                   8851:):                 foreach my $part (@{ $partlist }) {
                   8852:):                     my @types = $res->responseType($part);
                   8853:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8854:):                         $needs_hand_bubbles = 1;
                   8855:):                         last;
                   8856:):                     }
                   8857:):                 }
                   8858:):             }
                   8859:):         }
                   8860:):     }
                   8861:):     if ($needs_hand_bubbles) {
          9(raebur 8862:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8863:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8864:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8865:):                &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 />').
                   8866:):                '<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;'.
          8(raebur 8867:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8868:):     }
                   8869:):     return;
                   8870:): }
1.423     albertel 8871: 
1.82      albertel 8872: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8873:0):     my ($r,$symb) = @_;
1.513     foxr     8874: 
1.257     albertel 8875:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8876:     if (!$symb) {
                   8877: 	return '';
                   8878:     }
1.324     albertel 8879:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8880: 
1.596.2.12.2.  9(raebur 8881:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8882:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8883:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8884:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8885:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8886:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8887:     unless (ref($navmap)) {
                   8888:         $r->print(&navmap_errormsg());
                   8889:         return '';
1.596.2.12.2.  6(raebur 8890:3):     }
1.83      albertel 8891:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8892:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
          0(raebur 8893:2):         %grader_randomlists_by_symb,%symb_for_examcode);
          1(raebur 8894:2):     if (ref($map)) {
                   8895:2):         $randomorder = $map->randomorder();
          6(raebur 8896:3):         $randompick = $map->randompick();
          0(raebur 8897:2):         unless ($randomorder || $randompick) {
                   8898:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8899:2):                 if ($res->randomorder()) {
                   8900:2):                     $randomorder = 1;
                   8901:2):                 }
                   8902:2):                 if ($res->randompick()) {
                   8903:2):                     $randompick = 1;
                   8904:2):                 }
                   8905:2):                 last if ($randomorder || $randompick);
                   8906:2):             }
                   8907:2):         }
          6(raebur 8908:3):     } else {
                   8909:3):         $r->print(&navmap_errormsg());
                   8910:3):         return '';
          1(raebur 8911:2):     }
          6(raebur 8912:3):     my $nav_error;
1.83      albertel 8913:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8914:3):     if ($randomorder || $randompick) {
          0(raebur 8915:2):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
          6(raebur 8916:3):         if ($nav_error) {
                   8917:3):             $r->print(&navmap_errormsg());
                   8918:3):             return '';
1.586     raeburn  8919:         }
                   8920:     }
1.596.2.12.2.  6(raebur 8921:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8922:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8923: 
1.554     raeburn  8924:     my ($uname,$udom);
1.82      albertel 8925:     my $result= <<SCANTRONFORM;
1.81      albertel 8926: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8927:   <input type="hidden" name="command" value="scantron_configphase" />
                   8928:   $default_form_data
                   8929: SCANTRONFORM
1.82      albertel 8930:     $r->print($result);
                   8931: 
                   8932:     my @delayqueue;
1.542     raeburn  8933:     my (%completedstudents,%scandata);
1.140     albertel 8934:     
1.520     www      8935:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8936:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8937:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 8938:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8939:     $r->print('<br />');
1.140     albertel 8940:     my $start=&Time::HiRes::time();
1.158     albertel 8941:     my $i=-1;
1.542     raeburn  8942:     my $started;
1.447     foxr     8943: 
1.596.2.12.2.  (raeburn 8944:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8945:     if ($nav_error) {
                   8946:         $r->print(&navmap_errormsg());
                   8947:         return '';
                   8948:     }
                   8949: 
1.513     foxr     8950:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8951:     # the user and return.
                   8952: 
                   8953:     if ($ssi_error) {
                   8954: 	$r->print("</form>");
                   8955: 	&ssi_print_error($r);
1.520     www      8956:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8957: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8958:     }
1.447     foxr     8959: 
1.596.2.12.2.  9(raebur 8960:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8961:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8962:3):     my %orderedforcode;
1.542     raeburn  8963: 
1.157     albertel 8964:     while ($i<$scanlines->{'count'}) {
                   8965:  	($uname,$udom)=('','');
                   8966:  	$i++;
1.200     albertel 8967:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8968:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8969: 	if ($started) {
1.596.2.12.2.  1(raebur 8970:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8971: 	}
                   8972: 	$started=1;
1.596.2.12.2.  6(raebur 8973:3):         my %respnumlookup = ();
                   8974:3):         my %startline = ();
                   8975:3):         my $total;
1.157     albertel 8976:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8977:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8978:3):                                                  $randompick,$sequence,\@master_seq,
                   8979:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8980:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8981:3):                                                  \$total);
1.157     albertel 8982:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8983:  					      \%idmap,$i)) {
                   8984:   	    &scantron_add_delay(\@delayqueue,$line,
                   8985:  				'Unable to find a student that matches',1);
                   8986:  	    next;
                   8987:   	}
                   8988:  	if (exists $completedstudents{$uname}) {
                   8989:  	    &scantron_add_delay(\@delayqueue,$line,
                   8990:  				'Student '.$uname.' has multiple sheets',2);
                   8991:  	    next;
                   8992:  	}
1.596.2.12.2.  1(raebur 8993:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8994:2):         my $user = $uname.':'.$usec;
1.157     albertel 8995:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8996: 
1.596.2.12.2.  1(raebur 8997:2):         my $scancode;
                   8998:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8999:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9000:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9001:2):         } else {
                   9002:2):             $scancode = '';
                   9003:2):         }
                   9004:2): 
                   9005:2):         my @mapresources = @resources;
          6(raebur 9006:3):         if ($randomorder || $randompick) {
          1(raebur 9007:2):             @mapresources =
          6(raebur 9008:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9009:3):                              \%orderedforcode);
          1(raebur 9010:2):         }
1.586     raeburn  9011:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 9012:2):         foreach my $resource (@mapresources) {
1.586     raeburn  9013:             my $ressymb;
                   9014:             if (ref($resource)) {
                   9015:                 $ressymb = $resource->symb();
                   9016:             } else {
                   9017:                 $res_error = 1;
                   9018:                 last;
                   9019:             }
1.557     raeburn  9020:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9021:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9022:7):                 my $currcode;
                   9023:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9024:7):                     $currcode = $scancode;
                   9025:7):                 }
1.557     raeburn  9026:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 9027:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 9028:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   9029:7):                                               $currcode);
1.557     raeburn  9030:                 $partids_by_symb{$ressymb} = $parts;
                   9031:             } else {
                   9032:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9033:             }
1.554     raeburn  9034:         }
                   9035: 
1.586     raeburn  9036:         if ($res_error) {
                   9037:             &scantron_add_delay(\@delayqueue,$line,
                   9038:                                 'An error occurred while grading student '.$uname,2);
                   9039:             next;
                   9040:         }
                   9041: 
1.330     albertel 9042: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9043:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9044: 
                   9045: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9046: 	    &scantron_putfile($scanlines,$scan_data);
                   9047: 	}
1.161     albertel 9048: 	
1.542     raeburn  9049:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9050:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 9051:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   9052:3):                                    \%respnumlookup,\%startline) 
                   9053:3):             eq 'ssi_error') {
1.542     raeburn  9054:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9055:             $r->print("</form>");
                   9056:             &ssi_print_error($r);
                   9057:             &Apache::lonnet::remove_lock($lock);
                   9058:             return '';      # Why return ''?  Beats me.
                   9059:         }
1.513     foxr     9060: 
1.596.2.12.2.  6(raebur 9061:3):         if (($scancode) && ($randomorder || $randompick)) {
          0(raebur 9062:2):             foreach my $key (keys(%symb_for_examcode)) {
                   9063:2):                 my $symb_in_map = $symb_for_examcode{$key};
                   9064:2):                 if ($symb_in_map ne '') {
                   9065:2):                     my $parmresult =
                   9066:2):                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9067:2):                                                                '0_examcode',2,$scancode,
                   9068:2):                                                                'string_examcode',$uname,
                   9069:2):                                                                $udom);
                   9070:2):                 }
                   9071:2):             }
          6(raebur 9072:3):         }
1.140     albertel 9073: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9074:         if ($env{'form.verifyrecord'}) {
                   9075:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 9076:3):             if ($randompick) {
                   9077:3):                 if ($total) {
                   9078:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   9079:3):                 }
                   9080:3):             }
                   9081:3): 
1.542     raeburn  9082:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9083:             chomp($studentdata);
                   9084:             $studentdata =~ s/\r$//;
                   9085:             my $studentrecord = '';
                   9086:             my $counter = -1;
1.596.2.12.2.  1(raebur 9087:2):             foreach my $resource (@mapresources) {
1.554     raeburn  9088:                 my $ressymb = $resource->symb();
1.542     raeburn  9089:                 ($counter,my $recording) =
                   9090:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9091:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9092:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9093:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9094:                 $studentrecord .= $recording;
                   9095:             }
                   9096:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9097:                 &Apache::lonxml::clear_problem_counter();
                   9098:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9099:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 9100:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   9101:3):                                            \%respnumlookup,\%startline)
                   9102:3):                     eq 'ssi_error') {
1.554     raeburn  9103:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9104:                     $r->print("</form>");
                   9105:                     &ssi_print_error($r);
                   9106:                     &Apache::lonnet::remove_lock($lock);
                   9107:                     delete($completedstudents{$uname});
                   9108:                     return '';
                   9109:                 }
1.542     raeburn  9110:                 $counter = -1;
                   9111:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 9112:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  9113:                     my $ressymb = $resource->symb();
1.542     raeburn  9114:                     ($counter,my $recording) =
                   9115:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9116:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9117:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   9118:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   9119:3):                                                  \%startline);
1.542     raeburn  9120:                     $studentrecord .= $recording;
                   9121:                 }
                   9122:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  9123:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9124:                     if ($scancode eq '') {
1.596.2.6  raeburn  9125:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9126:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9127:                     } else {
1.596.2.6  raeburn  9128:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9129:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9130:                     }
                   9131:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9132:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9133:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9134:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9135:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9136:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 9137:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9138:                               &Apache::loncommon::end_data_table_row().
                   9139:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9140:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9141:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9142:                               &Apache::loncommon::end_data_table_row().
                   9143:                               &Apache::loncommon::end_data_table().'</p>');
                   9144:                 } else {
                   9145:                     $r->print('<br /><span class="LC_warning">'.
                   9146:                              &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 />'.
                   9147:                              &mt("As a consequence, this user's submission history records two tries.").
                   9148:                                  '</span><br />');
                   9149:                 }
                   9150:             }
                   9151:         }
1.543     raeburn  9152:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9153:     } continue {
1.330     albertel 9154: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9155: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9156:     }
1.140     albertel 9157:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9158:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9159: #    my $lasttime = &Time::HiRes::time()-$start;
                   9160: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9161: 
1.200     albertel 9162:     $r->print("</form>");
1.157     albertel 9163:     return '';
1.75      albertel 9164: }
1.157     albertel 9165: 
1.557     raeburn  9166: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9167:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9168:):         $bubbles_per_row) = @_;
1.557     raeburn  9169:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9170:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9171:         foreach my $resource (@{$resources}) {
                   9172:             my $ressymb = $resource->symb();
                   9173:             my ($analysis,$parts) =
                   9174:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9175:):                                           $env{'user.name'},$env{'user.domain'},
                   9176:):                                           1,$bubbles_per_row);
1.557     raeburn  9177:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9178:             if (ref($analysis) eq 'HASH') {
                   9179:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9180:                     $grader_randomlists_by_symb->{$ressymb} =
                   9181:                         $analysis->{'parts_withrandomlist'};
                   9182:                 }
                   9183:             }
                   9184:         }
                   9185:     }
                   9186:     return;
                   9187: }
                   9188: 
1.596.2.12.2.  1(raebur 9189:2): =pod
                   9190:2): 
                   9191:2): =item users_order
                   9192:2): 
                   9193:2):   Returns array of resources in current map, ordered based on either CODE,
                   9194:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9195:2):   "NAMEd" exam.
                   9196:2): 
          6(raebur 9197:3):   Should be used when randomorder and/or randompick applied when the 
                   9198:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9199:3):   for the version of the exam the student received.
          1(raebur 9200:2): 
                   9201:2): =cut
                   9202:2): 
                   9203:2): sub users_order  {
          6(raebur 9204:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9205:2):     my @mapresources;
          6(raebur 9206:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9207:2):         return @mapresources;
                   9208:2):     }
          6(raebur 9209:3):     if ($scancode) {
                   9210:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9211:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9212:3):         } else {
                   9213:3):             $env{'form.CODE'} = $scancode;
                   9214:3):             my $actual_seq =
                   9215:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9216:3):                                                                $master_seq,
                   9217:3):                                                                $user,$scancode,1);
                   9218:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9219:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9220:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9221:3):                     if (@mapresources > 0) {
                   9222:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9223:3):                     }
                   9224:3):                 }
                   9225:3):             }
                   9226:3):             delete($env{'form.CODE'});
          1(raebur 9227:2):         }
                   9228:2):     } else {
                   9229:2):         my $actual_seq =
                   9230:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9231:2):                                                            $master_seq,
          5(raebur 9232:3):                                                            $user,undef,1);
          1(raebur 9233:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9234:2):             @mapresources =
                   9235:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9236:2):         }
          6(raebur 9237:3):     }
                   9238:3):     return @mapresources;
          1(raebur 9239:2): }
                   9240:2): 
1.542     raeburn  9241: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9242:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9243:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9244:3):     my $uselookup = 0;
                   9245:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9246:3):         (ref($startline) eq 'HASH')) {
                   9247:3):         $uselookup = 1;
                   9248:3):     }
                   9249:3): 
1.554     raeburn  9250:     if (ref($resources) eq 'ARRAY') {
                   9251:         my $count = 0;
                   9252:         foreach my $resource (@{$resources}) {
                   9253:             my $ressymb = $resource->symb();
                   9254:             my %form = ('submitted'      => 'scantron',
                   9255:                         'grade_target'   => 'grade',
                   9256:                         'grade_username' => $uname,
                   9257:                         'grade_domain'   => $udom,
                   9258:                         'grade_courseid' => $env{'request.course.id'},
                   9259:                         'grade_symb'     => $ressymb,
                   9260:                         'CODE'           => $scancode
                   9261:                        );
1.596.2.12.2.  (raeburn 9262:):             if ($bubbles_per_row ne '') {
                   9263:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9264:):             }
                   9265:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9266:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9267:):             }
1.554     raeburn  9268:             if (ref($parts) eq 'HASH') {
                   9269:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9270:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9271:3):                         if ($uselookup) {
                   9272:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9273:3):                         } else {
                   9274:3):                             $form{'scantron_questnum_start.'.$part} =
                   9275:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9276:3):                         }
1.554     raeburn  9277:                         $count++;
                   9278:                     }
                   9279:                 }
                   9280:             }
                   9281:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9282:             return 'ssi_error' if ($ssi_error);
                   9283:             last if (&Apache::loncommon::connection_aborted($r));
                   9284:         }
1.542     raeburn  9285:     }
                   9286:     return;
                   9287: }
                   9288: 
1.157     albertel 9289: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9290:0):     my ($r,$symb) = @_;
1.565     raeburn  9291:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9292:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9293:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9294:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9295:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9296: 							  'domainid',
1.565     raeburn  9297: 							  'coursename',$dom);
                   9298:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9299:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9300:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9301:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9302:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9303:     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.596.2.12.2.  6(raebur 9304:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9305:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9306:     function checkUpload(formname) {
                   9307: 	if (formname.upfile.value == "") {
1.579     raeburn  9308: 	    alert("'.$nofile_alert.'");
1.157     albertel 9309: 	    return false;
                   9310: 	}
1.565     raeburn  9311:         if (formname.courseid.value == "") {
1.579     raeburn  9312:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9313:             return false;
                   9314:         }
1.157     albertel 9315: 	formname.submit();
                   9316:     }
1.565     raeburn  9317: 
                   9318:     function ToSyllabus() {
                   9319:         var cdom = '."'$dom'".';
                   9320:         var cnum = document.rules.courseid.value;
                   9321:         if (cdom == "" || cdom == null) {
                   9322:             return;
                   9323:         }
                   9324:         if (cnum == "" || cnum == null) {
                   9325:            return;
                   9326:         }
                   9327:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9328:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9329:         return;
                   9330:     }
                   9331: 
1.596.2.12.2.  9(raebur 9332:9):     '.$formatjs.'
                   9333:9): '));
                   9334:9):     $r->print('
1.596.2.4  raeburn  9335: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9336: 
1.492     albertel 9337: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9338: '.$default_form_data.
                   9339:   &Apache::lonhtmlcommon::start_pick_box().
                   9340:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9341:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9342:   &Apache::lonhtmlcommon::row_closure().
                   9343:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9344:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9345:   &Apache::lonhtmlcommon::row_closure().
                   9346:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9347:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9348:9):   &Apache::lonhtmlcommon::row_closure());
                   9349:9):     if ($formatoptions) {
                   9350:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9351:9):                   &Apache::lonhtmlcommon::row_closure());
                   9352:9):     }
                   9353:9):     $r->print(
1.565     raeburn  9354:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9355:   '<input type="file" name="upfile" size="50" />'.
                   9356:   &Apache::lonhtmlcommon::row_closure(1).
                   9357:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9358: 
1.492     albertel 9359: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9360: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9361: </form>
1.492     albertel 9362: ');
1.157     albertel 9363:     return '';
                   9364: }
                   9365: 
1.596.2.12.2.  9(raebur 9366:9): sub scantron_upload_dataformat {
                   9367:9):     my ($dom) = @_;
                   9368:9):     my ($formatoptions,$formattitle,$formatjs);
                   9369:9):     $formatjs = <<'END';
                   9370:9): function toggleScantab(form) {
                   9371:9):    return;
                   9372:9): }
                   9373:9): END
                   9374:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9375:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9376:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9377:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9378:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9379:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9380:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9381:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9382:9):                             my ($onclick,$formatextra,$singleline);
                   9383:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9384:9):                             my $count = 0;
                   9385:9):                             foreach my $line (@lines) {
          0.2.1(ra 9386:an-23):                                 next if (($line =~ /^\#/) || ($line eq ''));
          9(raebur 9387:9):                                 $singleline = $line;
                   9388:9):                                 $count ++;
                   9389:9):                             }
                   9390:9):                             if ($count > 1) {
                   9391:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9392:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9393:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9394:9):                                                &scantron_scantab().'</span></div>';
                   9395:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9396:9):                                 $formatjs = <<"END";
                   9397:9): function toggleScantab(form) {
                   9398:9):     var divid = 'bubbletype';
                   9399:9):     if (document.getElementById(divid)) {
                   9400:9):         var radioname = 'fileformat';
                   9401:9):         var num = form.elements[radioname].length;
                   9402:9):         if (num) {
                   9403:9):             for (var i=0; i<num; i++) {
                   9404:9):                 if (form.elements[radioname][i].checked) {
                   9405:9):                     var chosen = form.elements[radioname][i].value;
                   9406:9):                     if (chosen == 'dat') {
                   9407:9):                         document.getElementById(divid).style.display = 'none';
                   9408:9):                     } else if (chosen == 'csv') {
                   9409:9):                         document.getElementById(divid).style.display = 'block';
                   9410:9):                     }
                   9411:9):                 }
                   9412:9):             }
                   9413:9):         }
                   9414:9):     }
                   9415:9):     return;
                   9416:9): }
                   9417:9): 
                   9418:9): END
                   9419:9):                             } elsif ($count == 1) {
                   9420:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9421:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9422:9):                             }
                   9423:9):                             $formattitle = &mt('File format');
                   9424:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9425:9):                                              &mt('Plain Text (no delimiters)').
                   9426:9):                                              '</label>'.('&nbsp;'x2).
                   9427:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9428:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9429:9):                         }
                   9430:9):                     }
                   9431:9):                 }
                   9432:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9433:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9434:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9435:9):                         $formattitle = &mt('Bubblesheet type');
                   9436:9):                         $formatoptions = &scantron_scantab();
                   9437:9):                     }
                   9438:9):                 }
                   9439:9):             }
                   9440:9):         }
                   9441:9):     }
                   9442:9):     return ($formatoptions,$formattitle,$formatjs);
                   9443:9): }
1.423     albertel 9444: 
1.157     albertel 9445: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9446:0):     my ($r,$symb) = @_;
1.182     albertel 9447:     my $doanotherupload=
                   9448: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9449: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9450: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9451: 	'</form>'."\n";
1.257     albertel 9452:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9453: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9454: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9455: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9456:0):         unless ($symb) {
1.182     albertel 9457: 	    $r->print($doanotherupload);
                   9458: 	}
1.162     albertel 9459: 	return '';
                   9460:     }
1.257     albertel 9461:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9462:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9463:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9464:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9465:3):         $r->print(
                   9466:3):             &Apache::lonhtmlcommon::confirm_success(
                   9467:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9468:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9469:     } else {
1.596.2.12.2.  9(raebur 9470:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9471:9):         my $parser;
                   9472:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9473:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9474:9):                 my $is_csv;
                   9475:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9476:9):                 if (@possibles > 1) {
                   9477:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9478:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9479:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9480:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9481:9):                                     $is_csv = 1;
                   9482:9):                                 }
                   9483:9):                             }
                   9484:9):                         }
                   9485:9):                     }
                   9486:9):                 } elsif (@possibles == 1) {
                   9487:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9488:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9489:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9490:9):                                 $is_csv = 1;
                   9491:9):                             }
                   9492:9):                         }
                   9493:9):                     }
                   9494:9):                 }
                   9495:9):                 if ($is_csv) {
                   9496:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9497:9):                 }
                   9498:9):             }
                   9499:9):         }
                   9500:9):         my $result =
                   9501:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9502:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9503: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9504:3):             $r->print(
                   9505:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9506:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9507:3):                         (length($env{'form.upfile'})-1),
                   9508:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9509:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9510:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9511:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9512: 	} else {
1.596.2.12.2.  5(raebur 9513:3):             $r->print(
                   9514:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9515:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9516:3):                           $result,
1.568     raeburn  9517: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9518: 	}
                   9519:     }
1.174     albertel 9520:     if ($symb) {
1.596.2.12.2.  1(raebur 9521:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9522:     } else {
1.182     albertel 9523: 	$r->print($doanotherupload);
1.174     albertel 9524:     }
1.157     albertel 9525:     return '';
                   9526: }
                   9527: 
1.567     raeburn  9528: sub validate_uploaded_scantron_file {
                   9529:     my ($cdom,$cname,$fname) = @_;
                   9530:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9531:     my @lines;
                   9532:     if ($scanlines ne '-1') {
                   9533:         @lines=split("\n",$scanlines,-1);
                   9534:     }
                   9535:     my $output;
                   9536:     if (@lines) {
                   9537:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9538:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9539:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9540:         my %idmap = &username_to_idmap($classlist);
                   9541:         foreach my $key (keys(%idmap)) {
                   9542:             my $lckey = lc($key);
                   9543:             $idmap{$lckey} = $idmap{$key};
                   9544:         }
                   9545:         my %unique_formats;
1.596.2.12.2.  9(raebur 9546:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9547:         foreach my $line (@formatlines) {
1.596.2.12.2.  0.2.1(ra 9548:an-23):             next if (($line =~ /^\#/) || ($line eq ''));
1.567     raeburn  9549:             my @config = split(/:/,$line);
                   9550:             my $idstart = $config[5];
                   9551:             my $idlength = $config[6];
                   9552:             if (($idstart ne '') && ($idlength > 0)) {
                   9553:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9554:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9555:                 } else {
                   9556:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9557:                 }
                   9558:             }
                   9559:         }
                   9560:         foreach my $key (keys(%unique_formats)) {
                   9561:             my ($idstart,$idlength) = split(':',$key);
                   9562:             %{$counts{$key}} = (
                   9563:                                'found'   => 0,
                   9564:                                'total'   => 0,
                   9565:                               );
                   9566:             foreach my $line (@lines) {
                   9567:                 next if ($line =~ /^#/);
                   9568:                 next if ($line =~ /^[\s\cz]*$/);
                   9569:                 my $id = substr($line,$idstart-1,$idlength);
                   9570:                 $id = lc($id);
                   9571:                 if (exists($idmap{$id})) {
                   9572:                     $counts{$key}{'found'} ++;
                   9573:                 }
                   9574:                 $counts{$key}{'total'} ++;
                   9575:             }
                   9576:             if ($counts{$key}{'total'}) {
                   9577:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9578:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9579:                     $max_match_pct = $percent_match;
                   9580:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9581:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9582:                     $max_match_count = $counts{$key}{'total'};
                   9583:                 }
                   9584:             }
                   9585:         }
                   9586:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9587:             my $format_descs;
                   9588:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9589:             for (my $i=0; $i<$numwithformat; $i++) {
                   9590:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9591:                 if ($i<$numwithformat-2) {
                   9592:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9593:                 } elsif ($i==$numwithformat-2) {
                   9594:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9595:                 } elsif ($i==$numwithformat-1) {
                   9596:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9597:                 }
                   9598:             }
                   9599:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9600:3):             $output .= '<br />';
                   9601:3):             if ($found_match_count == $max_match_count) {
                   9602:3):                 # 100% matching entries
                   9603:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9604:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9605:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9606:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9607:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9608:3):                     ' in the file (for the format defined for [_3]).',
                   9609:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9610:3):             } else {
                   9611:3):                 # Not all entries matching? -> Show warning and additional info
                   9612:3):                 $output .=
                   9613:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9614:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9615:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9616:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9617:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9618:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9619:3):                         ' in the file (for the format defined for [_3]).',
                   9620:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9621:3):                     '<p class="LC_info">'.
                   9622:3):                     &mt('A low percentage of matches results from one of the following:').
                   9623:3):                     '</p><ul>'.
                   9624:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9625:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9626:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9627:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9628:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9629:3):                     '</ul>';
                   9630:3):             }
1.567     raeburn  9631:         }
                   9632:     } else {
1.596.2.12.2.  5(raebur 9633:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9634:     }
                   9635:     return $output;
                   9636: }
                   9637: 
1.202     albertel 9638: sub valid_file {
                   9639:     my ($requested_file)=@_;
                   9640:     foreach my $filename (sort(&scantron_filenames())) {
                   9641: 	if ($requested_file eq $filename) { return 1; }
                   9642:     }
                   9643:     return 0;
                   9644: }
                   9645: 
                   9646: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9647:0):     my ($r,$symb) = @_;
          (raeburn 9648:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9649:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9650:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9651:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9652:     if (! &valid_file($file)) {
1.492     albertel 9653: 	$r->print('
1.202     albertel 9654: 	<p>
1.596.2.12.2.  3(raebur 9655:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9656:         </p>
1.492     albertel 9657: ');
1.202     albertel 9658: 	return;
                   9659:     }
                   9660:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9661:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9662:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9663:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9664:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9665:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9666:     $r->print('
1.202     albertel 9667:     <p>
1.596.2.12.2.  1(raebur 9668:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9669: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9670:     </p>
                   9671:     <p>
1.492     albertel 9672: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9673: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9674:     </p>
                   9675:     <p>
1.492     albertel 9676: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9677: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9678:     </p>
1.492     albertel 9679: ');
1.202     albertel 9680:     return '';
                   9681: }
1.157     albertel 9682: 
1.523     raeburn  9683: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9684:0):     my ($r,$symb) = @_;
1.523     raeburn  9685:     if (!$symb) {return '';}
                   9686:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9687:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9688:     my $numletts = scalar(keys(%lettdig));
                   9689:     my $cnum = $env{'course.'.$cid.'.num'};
                   9690:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9691:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9692:     my %record;
                   9693:     my %scantron_config =
1.596.2.12.2.  9(raebur 9694:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9695:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9696:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9697:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9698:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9699:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9700:     unless (ref($navmap)) {
                   9701:         $r->print(&navmap_errormsg());
                   9702:         return '';
                   9703:     }
1.523     raeburn  9704:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9705:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9706:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9707:2):     if (ref($map)) {
                   9708:2):         $randomorder=$map->randomorder();
          7(raebur 9709:3):         $randompick=$map->randompick();
          0(raebur 9710:2):         unless ($randomorder || $randompick) {
                   9711:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9712:2):                 if ($res->randomorder()) {
                   9713:2):                     $randomorder = 1;
                   9714:2):                 }
                   9715:2):                 if ($res->randompick()) {
                   9716:2):                     $randompick = 1;
                   9717:2):                 }
                   9718:2):                 last if ($randomorder || $randompick);
                   9719:2):             }
                   9720:2):         }
          1(raebur 9721:2):     }
1.557     raeburn  9722:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9723:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9724:3):     if ($nav_error) {
                   9725:3):         $r->print(&navmap_errormsg());
                   9726:3):         return '';
          1(raebur 9727:2):     }
          (raeburn 9728:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9729:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9730:     my ($uname,$udom);
1.523     raeburn  9731:     my (%scandata,%lastname,%bylast);
                   9732:     $r->print('
                   9733: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9734: 
                   9735:     my @delayqueue;
                   9736:     my %completedstudents;
                   9737: 
1.596.2.12.2.  6(raebur 9738:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9739:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9740:3):     my ($username,$domain,$started);
          (raeburn 9741:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9742:     if ($nav_error) {
                   9743:         $r->print(&navmap_errormsg());
                   9744:         return '';
                   9745:     }
1.523     raeburn  9746: 
                   9747:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9748:                                           'Processing first student');
                   9749:     my $start=&Time::HiRes::time();
                   9750:     my $i=-1;
                   9751: 
                   9752:     while ($i<$scanlines->{'count'}) {
                   9753:         ($username,$domain,$uname)=('','','');
                   9754:         $i++;
                   9755:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9756:         if ($line=~/^[\s\cz]*$/) { next; }
                   9757:         if ($started) {
                   9758:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9759:                                                      'last student');
                   9760:         }
                   9761:         $started=1;
                   9762:         my $scan_record=
                   9763:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9764:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9765:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9766:3):                                               \%idmap,$i)) {
1.523     raeburn  9767:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9768:                                 'Unable to find a student that matches',1);
                   9769:             next;
                   9770:         }
                   9771:         if (exists $completedstudents{$uname}) {
                   9772:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9773:                                 'Student '.$uname.' has multiple sheets',2);
                   9774:             next;
                   9775:         }
                   9776:         my $pid = $scan_record->{'scantron.ID'};
                   9777:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9778:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9779:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9780:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9781:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9782:2): 
                   9783:2):         my $scancode;
                   9784:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9785:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9786:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9787:2):         } else {
                   9788:2):             $scancode = '';
                   9789:2):         }
                   9790:2): 
                   9791:2):         my @mapresources = @resources;
          6(raebur 9792:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9793:3):         my %respnumlookup=();
                   9794:3):         my %startline=();
                   9795:3):         if ($randomorder || $randompick) {
          1(raebur 9796:2):             @mapresources =
          6(raebur 9797:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9798:3):                              \%orderedforcode);
                   9799:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9800:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9801:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9802:3):                                              \%respnumlookup,\%startline);
                   9803:3):             if ($randompick && $total) {
                   9804:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9805:3):             }
          1(raebur 9806:2):         }
          6(raebur 9807:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9808:3):         chomp($scandata{$pid});
                   9809:3):         $scandata{$pid} =~ s/\r$//;
                   9810:3): 
1.523     raeburn  9811:         my $counter = -1;
1.596.2.12.2.  1(raebur 9812:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9813:             my $parts;
1.554     raeburn  9814:             my $ressymb = $resource->symb();
1.557     raeburn  9815:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9816:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9817:7):                 my $currcode;
                   9818:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9819:7):                     $currcode = $scancode;
                   9820:7):                 }
1.557     raeburn  9821:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9822:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9823:):                                               $username,$domain,undef,
          1(raebur 9824:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9825:             } else {
                   9826:                 $parts = $grader_partids_by_symb{$ressymb};
                   9827:             }
1.542     raeburn  9828:             ($counter,my $recording) =
                   9829:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9830:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9831:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9832:3):                                          $randomorder,$randompick,
                   9833:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9834:             $record{$pid} .= $recording;
1.523     raeburn  9835:         }
                   9836:     }
                   9837:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9838:     $r->print('<br />');
                   9839:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9840:     $passed = 0;
                   9841:     $failed = 0;
                   9842:     $numstudents = 0;
                   9843:     foreach my $last (sort(keys(%bylast))) {
                   9844:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9845:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9846:                 my $showscandata = $scandata{$pid};
                   9847:                 my $showrecord = $record{$pid};
                   9848:                 $showscandata =~ s/\s/&nbsp;/g;
                   9849:                 $showrecord =~ s/\s/&nbsp;/g;
                   9850:                 if ($scandata{$pid} eq $record{$pid}) {
                   9851:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9852:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9853: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9854: '</tr>'."\n".
                   9855: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9856:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9857:                     $passed ++;
                   9858:                 } else {
                   9859:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9860:                     $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  9861: '</tr>'."\n".
                   9862: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9863:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9864: '</tr>'."\n";
                   9865:                     $failed ++;
                   9866:                 }
                   9867:                 $numstudents ++;
                   9868:             }
                   9869:         }
                   9870:     }
1.596.2.4  raeburn  9871:     $r->print('<p>'.
1.596.2.8  raeburn  9872:               &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).',
1.596.2.4  raeburn  9873:                   '<b>',
                   9874:                   $numstudents,
                   9875:                   '</b>',
                   9876:                   $env{'form.scantron_maxbubble'}).
                   9877:               '</p>'
                   9878:     );
1.596.2.12.2.  2(raebur 9879:2):     $r->print('<p>'
                   9880:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9881:2):              .'<br />'
                   9882:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9883:2):              .'</p>');
1.523     raeburn  9884:     if ($passed) {
1.572     www      9885:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9886:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9887:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9888:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9889:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9890:                  $okstudents."\n".
                   9891:                  &Apache::loncommon::end_data_table().'<br />');
                   9892:     }
                   9893:     if ($failed) {
1.572     www      9894:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9895:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9896:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9897:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9898:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9899:                  $badstudents."\n".
                   9900:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9901:                  &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  9902:     }
1.596.2.12.2.  1(raebur 9903:0):     $r->print('</form><br />');
1.523     raeburn  9904:     return;
                   9905: }
                   9906: 
1.542     raeburn  9907: sub verify_scantron_grading {
1.554     raeburn  9908:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9909:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9910:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9911:     my ($record,%expected,%startpos);
                   9912:     return ($counter,$record) if (!ref($resource));
                   9913:     return ($counter,$record) if (!$resource->is_problem());
                   9914:     my $symb = $resource->symb();
1.554     raeburn  9915:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9916:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9917:         $counter ++;
                   9918:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9919:3):         my $respnum = $counter;
                   9920:3):         if ($randomorder || $randompick) {
                   9921:3):             $respnum = $respnumlookup->{$counter};
                   9922:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9923:3):         } else {
                   9924:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9925:3):         }
                   9926:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9927:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9928:             foreach my $item (@sub_lines) {
                   9929:                 $expected{$part_id} += $item;
                   9930:             }
                   9931:         } else {
1.596.2.12.2.  6(raebur 9932:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9933:         }
                   9934:     }
                   9935:     if ($symb) {
                   9936:         my %recorded;
                   9937:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9938:         if ($returnhash{'version'}) {
                   9939:             my %lasthash=();
                   9940:             my $version;
                   9941:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9942:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9943:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9944:                 }
                   9945:             }
                   9946:             foreach my $key (keys(%lasthash)) {
                   9947:                 if ($key =~ /\.scantron$/) {
                   9948:                     my $value = &unescape($lasthash{$key});
                   9949:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9950:                     if ($value eq '') {
                   9951:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9952:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9953:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9954:                             }
                   9955:                         }
                   9956:                     } else {
                   9957:                         my @tocheck;
                   9958:                         my @items = split(//,$value);
                   9959:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9960:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9961:                             if (@items < $expected{$part_id}) {
                   9962:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9963:                                 my @singles = split(//,$fragment);
                   9964:                                 foreach my $pos (@singles) {
                   9965:                                     if ($pos eq ' ') {
                   9966:                                         push(@tocheck,$pos);
                   9967:                                     } else {
                   9968:                                         my $next = shift(@items);
                   9969:                                         push(@tocheck,$next);
                   9970:                                     }
                   9971:                                 }
                   9972:                             } else {
                   9973:                                 @tocheck = @items;
                   9974:                             }
                   9975:                             foreach my $letter (@tocheck) {
                   9976:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9977:                                     if ($letter !~ /^[A-J]$/) {
                   9978:                                         $letter = $scantron_config->{'Qoff'};
                   9979:                                     }
                   9980:                                     $recorded{$part_id} .= $letter;
                   9981:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9982:                                     my $digit;
                   9983:                                     if ($letter !~ /^[A-J]$/) {
                   9984:                                         $digit = $scantron_config->{'Qoff'};
                   9985:                                     } else {
                   9986:                                         $digit = $lettdig->{$letter};
                   9987:                                     }
                   9988:                                     $recorded{$part_id} .= $digit;
                   9989:                                 }
                   9990:                             }
                   9991:                         } else {
                   9992:                             @tocheck = @items;
                   9993:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9994:                                 my $curr_sub = shift(@tocheck);
                   9995:                                 my $digit;
                   9996:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9997:                                     $digit = $lettdig->{$curr_sub}-1;
                   9998:                                 }
                   9999:                                 if ($curr_sub eq 'J') {
                   10000:                                     $digit += scalar($numletts);
                   10001:                                 }
                   10002:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10003:                                     if ($j == $digit) {
                   10004:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10005:                                     } else {
                   10006:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10007:                                     }
                   10008:                                 }
                   10009:                             }
                   10010:                         }
                   10011:                     }
                   10012:                 }
                   10013:             }
                   10014:         }
1.554     raeburn  10015:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10016:             if ($recorded{$part_id} eq '') {
                   10017:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10018:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10019:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10020:                     }
                   10021:                 }
                   10022:             }
                   10023:             $record .= $recorded{$part_id};
                   10024:         }
                   10025:     }
                   10026:     return ($counter,$record);
                   10027: }
                   10028: 
1.75      albertel 10029: #-------- end of section for handling grading scantron forms -------
                   10030: #
                   10031: #-------------------------------------------------------------------
                   10032: 
1.72      ng       10033: #-------------------------- Menu interface -------------------------
                   10034: #
1.596.2.12.2.  (raeburn 10035:): #--- Href with symb and command ---
                   10036:): 
                   10037:): sub href_symb_cmd {
                   10038:):     my ($symb,$cmd)=@_;
                   10039:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   10040:): }
                   10041:): 
1.443     banghart 10042: sub grading_menu {
1.596.2.12.2.  1(raebur 10043:0):     my ($request,$symb) = @_;
1.443     banghart 10044:     if (!$symb) {return '';}
                   10045: 
                   10046:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 10047:0):                   'command'=>'individual');
                   10048:0): 
                   10049:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10050:0): 
                   10051:0):     $fields{'command'}='ungraded';
                   10052:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10053:0): 
                   10054:0):     $fields{'command'}='table';
                   10055:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10056:0): 
                   10057:0):     $fields{'command'}='all_for_one';
                   10058:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10059:0): 
                   10060:0):     $fields{'command'}='downloadfilesselect';
                   10061:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10062:     
1.443     banghart 10063:     $fields{'command'} = 'csvform';
1.538     schulted 10064:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10065:     
1.443     banghart 10066:     $fields{'command'} = 'processclicker';
1.538     schulted 10067:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10068:     
1.443     banghart 10069:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10070:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 10071:0): 
                   10072:0):     $fields{'command'} = 'initialverifyreceipt';
                   10073:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 10074:1): 
                   10075:1):     my %permissions;
                   10076:1):     if ($perm{'mgr'}) {
                   10077:1):         $permissions{'either'} = 'F';
                   10078:1):         $permissions{'mgr'} = 'F';
                   10079:1):     }
                   10080:1):     if ($perm{'vgr'}) {
                   10081:1):         $permissions{'either'} = 'F';
                   10082:1):         $permissions{'vgr'} = 'F';
                   10083:1):     }
                   10084:1): 
          1(raebur 10085:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10086:             items =>[
1.596.2.12.2.  1(raebur 10087:0):                         {       linktext => 'Select individual students to grade',
                   10088:0):                                 url => $url1a,
          6(raebur 10089:1):                                 permission => $permissions{'either'},
          1(raebur 10090:0):                                 icon => 'grade_students.png',
                   10091:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   10092:0):                         },
                   10093:0):                         {       linktext => 'Grade ungraded submissions',
                   10094:0):                                 url => $url1b,
          6(raebur 10095:1):                                 permission => $permissions{'either'},
          1(raebur 10096:0):                                 icon => 'ungrade_sub.png',
                   10097:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   10098:0):                         },
                   10099:0): 
                   10100:0):                         {       linktext => 'Grading table',
                   10101:0):                                 url => $url1c,
          6(raebur 10102:1):                                 permission => $permissions{'either'},
          1(raebur 10103:0):                                 icon => 'grading_table.png',
                   10104:0):                                 linktitle => 'Grade current resource for all students.'
                   10105:0):                         },
                   10106:0):                         {       linktext => 'Grade page/folder for one student',
                   10107:0):                                 url => $url1d,
          6(raebur 10108:1):                                 permission => $permissions{'either'},
          1(raebur 10109:0):                                 icon => 'grade_PageFolder.png',
                   10110:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 10111:                         },
1.596.2.12.2.  3(raebur 10112:0):                         {       linktext => 'Download submitted files',
          1(raebur 10113:0):                                 url => $url1e,
          6(raebur 10114:1):                                 permission => $permissions{'either'},
          1(raebur 10115:0):                                 icon => 'download_sub.png',
          3(raebur 10116:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 10117:0):                         }]},
                   10118:0):                          { categorytitle=>'Automated Grading',
                   10119:0):                items =>[
                   10120:0): 
1.538     schulted 10121:                 	    {	linktext => 'Upload Scores',
                   10122:                     		url => $url2,
1.596.2.12.2.  6(raebur 10123:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10124:                     		icon => 'uploadscores.png',
                   10125:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10126:                 	    },
                   10127:                 	    {	linktext => 'Process Clicker',
                   10128:                     		url => $url3,
1.596.2.12.2.  6(raebur 10129:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10130:                     		icon => 'addClickerInfoFile.png',
                   10131:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10132:                 	    },
1.587     raeburn  10133:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10134:                     		url => $url4,
1.596.2.12.2.  6(raebur 10135:1):                     		permission => $permissions{'mgr'},
          1(raebur 10136:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  10137:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 10138:0):                 	    },
                   10139:0):                             {   linktext => 'Verify Receipt Number',
                   10140:0):                                 url => $url5,
          6(raebur 10141:1):                                 permission => $permissions{'either'},
          1(raebur 10142:0):                                 icon => 'receipt_number.png',
                   10143:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10144:0):                             }
                   10145:0): 
1.538     schulted 10146:                     ]
                   10147:             });
                   10148: 
1.443     banghart 10149:     # Create the menu
                   10150:     my $Str;
1.445     banghart 10151:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10152:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10153:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10154: 
1.596.2.12.2.  1(raebur 10155:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10156:     return $Str;    
                   10157: }
                   10158: 
1.596.2.12.2.  1(raebur 10159:0): sub ungraded {
                   10160:0):     my ($request)=@_;
                   10161:0):     &submit_options($request);
                   10162:0): }
1.443     banghart 10163: 
1.596.2.12.2.  1(raebur 10164:0): sub submit_options_sequence {
                   10165:0):     my ($request,$symb) = @_;
1.72      ng       10166:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10167:0):     &commonJSfunctions($request);
                   10168:0):     my $result;
1.72      ng       10169: 
1.596.2.12.2.  1(raebur 10170:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10171:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10172:0):     $result.=&selectfield(0).
                   10173:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10174:0):             <div>
                   10175:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10176:0):             </div>
                   10177:0):         </div>
                   10178:0):   </form>';
                   10179:0):     return $result;
                   10180:0): }
                   10181:0): 
                   10182:0): sub submit_options_table {
                   10183:0):     my ($request,$symb) = @_;
                   10184:0):     if (!$symb) {return '';}
1.118     ng       10185:     &commonJSfunctions($request);
1.473     albertel 10186:     my $result;
1.596.2.12.2.  1(raebur 10187:0): 
                   10188:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10189:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10190:0): 
                   10191:0):     $result.=&selectfield(1).
                   10192:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10193:0):             <div>
                   10194:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10195:0):             </div>
                   10196:0):         </div>
                   10197:0):   </form>';
                   10198:0):     return $result;
                   10199:0): }
                   10200:0): 
                   10201:0): sub submit_options_download {
                   10202:0):     my ($request,$symb) = @_;
                   10203:0):     if (!$symb) {return '';}
                   10204:0): 
                   10205:0):     my $res_error;
                   10206:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10207:0):         &response_type($symb,\$res_error);
                   10208:0):     if ($res_error) {
                   10209:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10210:0):         return;
                   10211:0):     }
                   10212:0):     unless ($numessay) {
                   10213:0):         $request->print(&mt('No essayresponse items found'));
                   10214:0):         return;
                   10215:0):     }
                   10216:0):     my $table;
                   10217:0):     if (ref($partlist) eq 'ARRAY') {
                   10218:0):         if (scalar(@$partlist) > 1 ) {
                   10219:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10220:         }
                   10221:     }
                   10222: 
1.596.2.12.2.  1(raebur 10223:0):     &commonJSfunctions($request);
1.72      ng       10224: 
1.596.2.12.2.  1(raebur 10225:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10226:0):         $table."\n".
                   10227:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10228:     $result.='
1.533     bisitz   10229: <h2>
1.596.2.12.2.  3(raebur 10230:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          1(raebur 10231:0): </h2>'.&selectfield(1).'
                   10232:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10233:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10234:0):             </div>
                   10235:0):           </div>
                   10236:0): 
                   10237:0): 
                   10238:0):   </form>';
                   10239:0):     return $result;
                   10240:0): }
                   10241:0): 
                   10242:0): #--- Displays the submissions first page -------
                   10243:0): sub submit_options {
                   10244:0):     my ($request,$symb) = @_;
                   10245:0):     if (!$symb) {return '';}
                   10246:0): 
                   10247:0):     &commonJSfunctions($request);
                   10248:0):     my $result;
                   10249:0): 
                   10250:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10251:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10252:0):     $result.=&selectfield(1).'
                   10253:0):                 <input type="hidden" name="command" value="submission" />
                   10254:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10255:0):             </div>
                   10256:0):           </div>
                   10257:0):   </form>';
                   10258:0):     return $result;
                   10259:0): }
                   10260:0): 
                   10261:0): sub selectfield {
                   10262:0):    my ($full)=@_;
                   10263:0):    my %options =
                   10264:0):        (&substatus_options,
                   10265:0):         'select_form_order' => ['yes','queued','graded','incorrect','all']);
          7(raebur 10266:1): 
                   10267:1):   #
                   10268:1):   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10269:1):   # for a different course from the @Sections global in lonstatistics.pm,
                   10270:1):   # populated by an earlier request.
                   10271:1):   #
                   10272:1):    &Apache::lonstatistics::PrepareClasslist();
                   10273:1): 
          1(raebur 10274:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10275: 
                   10276:     <fieldset>
                   10277:       <legend>
                   10278:        '.&mt('Sections').'
                   10279:       </legend>
1.596.2.12.2.  1(raebur 10280:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10281:     </fieldset>
1.596.2.12.2.  1(raebur 10282:0): 
1.533     bisitz   10283:     <fieldset>
                   10284:       <legend>
                   10285:         '.&mt('Groups').'
                   10286:       </legend>
                   10287:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10288:     </fieldset>
1.596.2.12.2.  1(raebur 10289:0):  
1.533     bisitz   10290:     <fieldset>
                   10291:       <legend>
                   10292:         '.&mt('Access Status').'
                   10293:       </legend>
1.596.2.12.2.  1(raebur 10294:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10295:0):     </fieldset>';
                   10296:0):     if ($full) {
                   10297:0):         $result.='
1.533     bisitz   10298:     <fieldset>
                   10299:       <legend>
                   10300:         '.&mt('Submission Status').'
1.596.2.12.2.  1(raebur 10301:0):       </legend>'.
                   10302:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10303:0):    '</fieldset>';
                   10304:0):     }
                   10305:0):     $result.='</div><br />';
1.44      ng       10306:     return $result;
1.2       albertel 10307: }
                   10308: 
1.596.2.12.2.  7(raebur 10309:6): sub substatus_options {
                   10310:6):     return &Apache::lonlocal::texthash(
                   10311:6):                                       'yes'       => 'with submissions',
                   10312:6):                                       'queued'    => 'in grading queue',
                   10313:6):                                       'graded'    => 'with ungraded submissions',
                   10314:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10315:7):                                       'all'       => 'with any status',
                   10316:7):                                       );
          7(raebur 10317:6): }
                   10318:6): 
          1(raebur 10319:0): sub transtatus_options {
                   10320:0):     return &Apache::lonlocal::texthash(
                   10321:0):                                        'yes'       => 'with score transactions',
                   10322:0):                                        'incorrect' => 'with less than full credit',
                   10323:0):                                        'all'       => 'with any status',
                   10324:0):                                       );
                   10325:0): }
                   10326:0): 
1.285     albertel 10327: sub reset_perm {
                   10328:     undef(%perm);
                   10329: }
                   10330: 
                   10331: sub init_perm {
                   10332:     &reset_perm();
1.300     albertel 10333:     foreach my $test_perm ('vgr','mgr','opa') {
                   10334: 
                   10335: 	my $scope = $env{'request.course.id'};
                   10336: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10337: 
                   10338: 	    $scope .= '/'.$env{'request.course.sec'};
                   10339: 	    if ( $perm{$test_perm}=
                   10340: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10341: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10342: 	    } else {
                   10343: 		delete($perm{$test_perm});
                   10344: 	    }
1.285     albertel 10345: 	}
                   10346:     }
                   10347: }
                   10348: 
1.596.2.12.2.  (raeburn 10349:): sub init_old_essays {
                   10350:):     my ($symb,$apath,$adom,$aname) = @_;
                   10351:):     if ($symb ne '') {
                   10352:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10353:):         if (keys(%essays) > 0) {
                   10354:):             $old_essays{$symb} = \%essays;
                   10355:):         }
                   10356:):     }
                   10357:):     return;
                   10358:): }
                   10359:): 
                   10360:): sub reset_old_essays {
                   10361:):     undef(%old_essays);
                   10362:): }
                   10363:): 
1.400     www      10364: sub gather_clicker_ids {
1.408     albertel 10365:     my %clicker_ids;
1.400     www      10366: 
                   10367:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10368: 
                   10369:     # Set up a couple variables.
1.407     albertel 10370:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10371:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10372:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10373: 
1.407     albertel 10374:     foreach my $student (keys(%$classlist)) {
1.438     www      10375:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10376:         my $username = $classlist->{$student}->[$username_idx];
                   10377:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10378:         my $clickers =
1.408     albertel 10379: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10380:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10381:             $id=~s/^[\#0]+//;
1.421     www      10382:             $id=~s/[\-\:]//g;
1.407     albertel 10383:             if (exists($clicker_ids{$id})) {
1.408     albertel 10384: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10385:             } else {
1.408     albertel 10386: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10387:             }
                   10388:         }
                   10389:     }
1.407     albertel 10390:     return %clicker_ids;
1.400     www      10391: }
                   10392: 
1.402     www      10393: sub gather_adv_clicker_ids {
1.408     albertel 10394:     my %clicker_ids;
1.402     www      10395:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10396:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10397:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10398:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10399:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10400:             my ($puname,$pudom)=split(/\:/,$person);
                   10401:             my $clickers =
1.408     albertel 10402: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10403:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10404: 		$id=~s/^[\#0]+//;
1.421     www      10405:                 $id=~s/[\-\:]//g;
1.408     albertel 10406: 		if (exists($clicker_ids{$id})) {
                   10407: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10408: 		} else {
                   10409: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10410: 		}
1.405     www      10411:             }
1.402     www      10412:         }
                   10413:     }
1.407     albertel 10414:     return %clicker_ids;
1.402     www      10415: }
                   10416: 
1.413     www      10417: sub clicker_grading_parameters {
                   10418:     return ('gradingmechanism' => 'scalar',
                   10419:             'upfiletype' => 'scalar',
                   10420:             'specificid' => 'scalar',
                   10421:             'pcorrect' => 'scalar',
                   10422:             'pincorrect' => 'scalar');
                   10423: }
                   10424: 
1.400     www      10425: sub process_clicker {
1.596.2.12.2.  1(raebur 10426:0):     my ($r,$symb)=@_;
1.400     www      10427:     if (!$symb) {return '';}
                   10428:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10429:0):     $result.=&Apache::loncommon::start_data_table().
                   10430:0):              &Apache::loncommon::start_data_table_header_row().
                   10431:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10432:0):              &Apache::loncommon::end_data_table_header_row().
                   10433:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10434: # Attempt to restore parameters from last session, set defaults if not present
                   10435:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10436:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10437:                                                  \%Saveable_Parameters);
                   10438:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10439:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10440:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10441:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10442: 
                   10443:     my %checked;
1.521     www      10444:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10445:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10446:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10447:        }
                   10448:     }
                   10449: 
1.596.2.12.2.  1(raebur 10450:0):     my $upload=&mt("Evaluate File");
1.400     www      10451:     my $type=&mt("Type");
1.402     www      10452:     my $attendance=&mt("Award points just for participation");
                   10453:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10454:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10455:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10456:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10457:     my $pcorrect=&mt("Percentage points for correct solution");
                   10458:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10459:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10460:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10461:):                                                     'interwrite' => 'interwrite PRS',
                   10462:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10463:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10464:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10465: function sanitycheck() {
                   10466: // Accept only integer percentages
                   10467:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10468:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10469: // Find out grading choice
                   10470:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10471:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10472:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10473:       }
                   10474:    }
                   10475: // By default, new choice equals user selection
                   10476:    newgradingchoice=gradingchoice;
                   10477: // Not good to give more points for false answers than correct ones
                   10478:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10479:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10480:    }
                   10481: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10482:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10483:       document.forms.gradesupload.pcorrect.value=100;
                   10484:       document.forms.gradesupload.pincorrect.value=100;
                   10485:    }
                   10486: // If the values are different, cannot be attendance only
                   10487:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10488:        (gradingchoice=='attendance')) {
                   10489:        newgradingchoice='personnel';
                   10490:    }
                   10491: // Change grading choice to new one
                   10492:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10493:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10494:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10495:       } else {
                   10496:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10497:       }
                   10498:    }
                   10499: // Remember the old state
                   10500:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10501: }
1.596.2.12.2.  1(raebur 10502:0): ENDUPFORM
                   10503:0):     $result.= <<ENDUPFORM;
1.400     www      10504: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10505: <input type="hidden" name="symb" value="$symb" />
                   10506: <input type="hidden" name="command" value="processclickerfile" />
                   10507: <input type="file" name="upfile" size="50" />
                   10508: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10509:0): ENDUPFORM
                   10510:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10511:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10512:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10513: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10514: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10515: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10516: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10517: <br />&nbsp;&nbsp;&nbsp;
                   10518: <input type="text" name="givenanswer" size="50" />
1.413     www      10519: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10520:0): ENDGRADINGFORM
                   10521:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10522:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10523:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10524: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10525: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10526: </form>
1.596.2.12.2.  1(raebur 10527:0): ENDPERCFORM
                   10528:0):     $result.='</td>'.
                   10529:0):              &Apache::loncommon::end_data_table_row().
                   10530:0):              &Apache::loncommon::end_data_table();
1.400     www      10531:     return $result;
                   10532: }
                   10533: 
                   10534: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10535:0):     my ($r,$symb) = @_;
1.400     www      10536:     if (!$symb) {return '';}
1.413     www      10537: 
                   10538:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10539:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10540:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10541:0):     my $result='';
1.404     www      10542:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10543: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10544:0): 	return $result;
1.404     www      10545:     }
1.522     www      10546:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10547:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10548:0):         return $result;
1.521     www      10549:     }
1.522     www      10550:     my $foundgiven=0;
1.521     www      10551:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10552:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10553:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10554:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10555:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10556:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10557:         $foundgiven=$#answers+1;
1.521     www      10558:     }
1.407     albertel 10559:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10560:     my %correct_ids;
1.404     www      10561:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10562: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10563:     }
                   10564:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10565: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10566: 	   $correct_id=~tr/a-z/A-Z/;
                   10567: 	   $correct_id=~s/\s//gs;
                   10568: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10569:            $correct_id=~s/[\-\:]//g;
1.414     www      10570:            if ($correct_id) {
                   10571: 	      $correct_ids{$correct_id}='specified';
                   10572:            }
                   10573:         }
1.400     www      10574:     }
1.404     www      10575:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10576: 	$result.=&mt('Score based on attendance only');
1.521     www      10577:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10578:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10579:     } else {
1.408     albertel 10580: 	my $number=0;
1.411     www      10581: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10582: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10583: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10584: 	    if ($correct_ids{$id} eq 'specified') {
                   10585: 		$result.=&mt('specified');
                   10586: 	    } else {
                   10587: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10588: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10589: 	    }
                   10590: 	    $number++;
                   10591: 	}
1.411     www      10592:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10593:3):         if ($number==0) {
                   10594:3):             $result .=
                   10595:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10596:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10597:0):             return $result;
          5(raebur 10598:3):         }
1.404     www      10599:     }
1.405     www      10600:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10601:3):         $result .=
                   10602:3):             &Apache::lonhtmlcommon::confirm_success(
                   10603:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10604:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10605:0):         return $result;
1.405     www      10606:     }
1.596.2.12.2.  7(raebur 10607:9):     my $mimetype;
                   10608:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10609:9):         my $mm = new File::MMagic;
                   10610:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10611:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10612:9):             $result.= '<p>'.
                   10613:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10614:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10615:0):             return $result;
          7(raebur 10616:9):         }
                   10617:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10618:9):         $result .= '<p>'.
                   10619:9):             &Apache::lonhtmlcommon::confirm_success(
                   10620:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10621:0):         return $result;
          7(raebur 10622:9):     }
1.410     www      10623: 
                   10624: # Were able to get all the info needed, now analyze the file
                   10625: 
1.411     www      10626:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10627:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10628:0):     $result.=&Apache::loncommon::start_data_table().
                   10629:0):              &Apache::loncommon::start_data_table_header_row().
                   10630:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10631:0):              &Apache::loncommon::end_data_table_header_row().
                   10632:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10633:0): <td>
1.410     www      10634: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10635: <input type="hidden" name="symb" value="$symb" />
                   10636: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10637: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10638: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10639: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10640: ENDHEADER
1.522     www      10641:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10642:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10643:     } 
1.408     albertel 10644:     my %responses;
                   10645:     my @questiontitles;
1.405     www      10646:     my $errormsg='';
                   10647:     my $number=0;
                   10648:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10649:9):         if ($mimetype eq 'text/plain') {
                   10650:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10651:9):         } elsif ($mimetype eq 'text/html') {
                   10652:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10653:9):         }
                   10654:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10655:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10656:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10657:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10658:):     }
1.411     www      10659:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10660:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10661:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10662:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10663:              '<br />';
1.522     www      10664:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10665:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.596.2.12.2.  1(raebur 10666:0):        return $result;
1.522     www      10667:     } 
1.414     www      10668: # Remember Question Titles
                   10669: # FIXME: Possibly need delimiter other than ":"
                   10670:     for (my $i=0;$i<$number;$i++) {
                   10671:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10672:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10673:     }
1.411     www      10674:     my $correct_count=0;
                   10675:     my $student_count=0;
                   10676:     my $unknown_count=0;
1.414     www      10677: # Match answers with usernames
                   10678: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10679:     foreach my $id (keys(%responses)) {
1.410     www      10680:        if ($correct_ids{$id}) {
1.414     www      10681:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10682:           $correct_count++;
1.410     www      10683:        } elsif ($clicker_ids{$id}) {
1.437     www      10684:           if ($clicker_ids{$id}=~/\,/) {
                   10685: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10686:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10687:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10688:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10689:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10690:                            "<select name='multi".$id."'>";
                   10691:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10692:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10693:              }
                   10694:              $result.='</select>';
                   10695:              $unknown_count++;
                   10696:           } else {
                   10697: # Good: found one and only one user with the right clicker
                   10698:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10699:              $student_count++;
                   10700:           }
1.410     www      10701:        } else {
1.596.2.12.2.  1(raebur 10702:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10703:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10704:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10705:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10706:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10707:                    "\n".&mt("Domain").": ".
                   10708:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10709:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10710:           $unknown_count++;
1.410     www      10711:        }
1.405     www      10712:     }
1.412     www      10713:     $result.='<hr />'.
                   10714:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10715:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10716:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10717:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10718:        } elsif ($correct_count>1) {
1.414     www      10719:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10720:        }
                   10721:     }
1.428     www      10722:     if ($number<1) {
                   10723:        $errormsg.="Found no questions.";
                   10724:     }
1.412     www      10725:     if ($errormsg) {
                   10726:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10727:     } else {
                   10728:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10729:     }
1.596.2.12.2.  1(raebur 10730:0):     $result.='</form></td>'.
                   10731:0):              &Apache::loncommon::end_data_table_row().
                   10732:0):              &Apache::loncommon::end_data_table();
                   10733:0):     return $result;
1.400     www      10734: }
                   10735: 
1.405     www      10736: sub iclicker_eval {
1.406     www      10737:     my ($questiontitles,$responses)=@_;
1.405     www      10738:     my $number=0;
                   10739:     my $errormsg='';
                   10740:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10741:         my %components=&Apache::loncommon::record_sep($line);
                   10742:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10743: 	if ($entries[0] eq 'Question') {
                   10744: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10745: 		$$questiontitles[$number]=$entries[$i];
                   10746: 		$number++;
                   10747: 	    }
                   10748: 	}
                   10749: 	if ($entries[0]=~/^\#/) {
                   10750: 	    my $id=$entries[0];
                   10751: 	    my @idresponses;
                   10752: 	    $id=~s/^[\#0]+//;
                   10753: 	    for (my $i=0;$i<$number;$i++) {
                   10754: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10755:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10756: 		push(@idresponses,$entries[$idx]);
                   10757: 	    }
                   10758: 	    $$responses{$id}=join(',',@idresponses);
                   10759: 	}
1.405     www      10760:     }
                   10761:     return ($errormsg,$number);
                   10762: }
                   10763: 
1.596.2.12.2.  7(raebur 10764:9): sub iclickerxml_eval {
                   10765:9):     my ($questiontitles,$responses)=@_;
                   10766:9):     my $number=0;
                   10767:9):     my $errormsg='';
                   10768:9):     my @state;
                   10769:9):     my %respbyid;
                   10770:9):     my $p = HTML::Parser->new
                   10771:9):     (
                   10772:9):         xml_mode => 1,
                   10773:9):         start_h =>
                   10774:9):             [sub {
                   10775:9):                  my ($tagname,$attr) = @_;
                   10776:9):                  push(@state,$tagname);
                   10777:9):                  if ("@state" eq "ssn p") {
                   10778:9):                      my $title = $attr->{qn};
                   10779:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10780:9):                      $questiontitles->[$number]=$title;
                   10781:9):                  } elsif ("@state" eq "ssn p v") {
                   10782:9):                      my $id = $attr->{id};
                   10783:9):                      my $entry = $attr->{ans};
                   10784:9):                      $id=~s/^[\#0]+//;
                   10785:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10786:9):                      $respbyid{$id}[$number] = $entry;
                   10787:9):                  }
                   10788:9):             }, "tagname, attr"],
                   10789:9):          end_h =>
                   10790:9):                [sub {
                   10791:9):                    my ($tagname) = @_;
                   10792:9):                    if ("@state" eq "ssn p") {
                   10793:9):                        $number++;
                   10794:9):                    }
                   10795:9):                    pop(@state);
                   10796:9):                 }, "tagname"],
                   10797:9):     );
                   10798:9): 
                   10799:9):     $p->parse($env{'form.upfile'});
                   10800:9):     $p->eof;
                   10801:9):     foreach my $id (keys(%respbyid)) {
                   10802:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10803:9):     }
                   10804:9):     return ($errormsg,$number);
                   10805:9): }
                   10806:9): 
1.419     www      10807: sub interwrite_eval {
                   10808:     my ($questiontitles,$responses)=@_;
                   10809:     my $number=0;
                   10810:     my $errormsg='';
1.420     www      10811:     my $skipline=1;
                   10812:     my $questionnumber=0;
                   10813:     my %idresponses=();
1.419     www      10814:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10815:         my %components=&Apache::loncommon::record_sep($line);
                   10816:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10817:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10818:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10819:         next if $skipline;
                   10820:         if ($entries[0]!=$questionnumber) {
                   10821:            $questionnumber=$entries[0];
                   10822:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10823:            $number++;
1.419     www      10824:         }
1.420     www      10825:         my $id=$entries[4];
                   10826:         $id=~s/^[\#0]+//;
1.421     www      10827:         $id=~s/^v\d*\://i;
                   10828:         $id=~s/[\-\:]//g;
1.420     www      10829:         $idresponses{$id}[$number]=$entries[6];
                   10830:     }
1.524     raeburn  10831:     foreach my $id (keys(%idresponses)) {
1.420     www      10832:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10833:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10834:     }
                   10835:     return ($errormsg,$number);
                   10836: }
                   10837: 
1.596.2.12.2.  (raeburn 10838:): sub turning_eval {
                   10839:):     my ($questiontitles,$responses)=@_;
                   10840:):     my $number=0;
                   10841:):     my $errormsg='';
                   10842:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10843:):         my %components=&Apache::loncommon::record_sep($line);
                   10844:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10845:):         if ($#entries>$number) { $number=$#entries; }
                   10846:):         my $id=$entries[0];
                   10847:):         my @idresponses;
                   10848:):         $id=~s/^[\#0]+//;
                   10849:):         unless ($id) { next; }
                   10850:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10851:):             $entries[$idx]=~s/\,/\;/g;
                   10852:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10853:):             push(@idresponses,$entries[$idx]);
                   10854:):         }
                   10855:):         $$responses{$id}=join(',',@idresponses);
                   10856:):     }
                   10857:):     for (my $i=1; $i<=$number; $i++) {
                   10858:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10859:):     }
                   10860:):     return ($errormsg,$number);
                   10861:): }
                   10862:): 
1.414     www      10863: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10864:0):     my ($r,$symb) = @_;
1.414     www      10865:     if (!$symb) {return '';}
1.416     www      10866: # See which part we are saving to
1.582     raeburn  10867:     my $res_error;
                   10868:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10869:     if ($res_error) {
                   10870:         return &navmap_errormsg();
                   10871:     }
1.416     www      10872: # FIXME: This should probably look for the first handgradeable part
                   10873:     my $part=$$partlist[0];
                   10874: # Start screen output
1.596.2.12.2.  1(raebur 10875:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10876:0):                  &Apache::loncommon::start_data_table_header_row().
                   10877:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10878:0):                  &Apache::loncommon::end_data_table_header_row().
                   10879:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10880: # Get correct result
                   10881: # FIXME: Possibly need delimiter other than ":"
                   10882:     my @correct=();
1.415     www      10883:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10884:     my $number=$env{'form.number'};
                   10885:     if ($gradingmechanism ne 'attendance') {
1.414     www      10886:        foreach my $key (keys(%env)) {
                   10887:           if ($key=~/^form\.correct\:/) {
                   10888:              my @input=split(/\,/,$env{$key});
                   10889:              for (my $i=0;$i<=$#input;$i++) {
                   10890:                  if (($correct[$i]) && ($input[$i]) &&
                   10891:                      ($correct[$i] ne $input[$i])) {
                   10892:                     $result.='<br /><span class="LC_warning">'.
                   10893:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10894:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10895:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10896:                     $correct[$i]=$input[$i];
                   10897:                  }
                   10898:              }
                   10899:           }
                   10900:        }
1.415     www      10901:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10902:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10903:              $result.='<br /><span class="LC_error">'.
                   10904:                       &mt('No correct result given for question "[_1]"!',
                   10905:                           $env{'form.question:'.$i}).'</span>';
                   10906:           }
                   10907:        }
1.596.2.4  raeburn  10908:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10909:     }
                   10910: # Start grading
1.415     www      10911:     my $pcorrect=$env{'form.pcorrect'};
                   10912:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10913:     my $storecount=0;
1.596.2.4  raeburn  10914:     my %users=();
1.415     www      10915:     foreach my $key (keys(%env)) {
1.420     www      10916:        my $user='';
1.415     www      10917:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10918:           $user=$1;
                   10919:        }
                   10920:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10921:           my $id=$1;
                   10922:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10923:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10924:           } elsif ($env{'form.multi'.$id}) {
                   10925:              $user=$env{'form.multi'.$id};
1.420     www      10926:           }
                   10927:        }
1.596.2.4  raeburn  10928:        if ($user) {
                   10929:           if ($users{$user}) {
                   10930:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10931:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10932:                       '</span><br />';
                   10933:           }
                   10934:           $users{$user}=1;
1.415     www      10935:           my @answer=split(/\,/,$env{$key});
                   10936:           my $sum=0;
1.522     www      10937:           my $realnumber=$number;
1.415     www      10938:           for (my $i=0;$i<$number;$i++) {
1.576     www      10939:              if  ($correct[$i] eq '-') {
                   10940:                 $realnumber--;
1.596.2.12.2.  1(raebur 10941:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      10942:                 if ($gradingmechanism eq 'attendance') {
                   10943:                    $sum+=$pcorrect;
1.576     www      10944:                 } elsif ($correct[$i] eq '*') {
1.522     www      10945:                    $sum+=$pcorrect;
1.415     www      10946:                 } else {
1.596.2.4  raeburn  10947: # We actually grade if correct or not
                   10948:                    my $increment=$pincorrect;
                   10949: # Special case: numerical answer "0"
                   10950:                    if ($correct[$i] eq '0') {
                   10951:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10952:                          $increment=$pcorrect;
                   10953:                       }
                   10954: # General numerical answer, both evaluate to something non-zero
                   10955:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10956:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10957:                          $increment=$pcorrect;
                   10958:                       }
                   10959: # Must be just alphanumeric
                   10960:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10961:                       $increment=$pcorrect;
1.415     www      10962:                    }
1.596.2.4  raeburn  10963:                    $sum+=$increment;
1.415     www      10964:                 }
                   10965:              }
                   10966:           }
1.522     www      10967:           my $ave=$sum/(100*$realnumber);
1.416     www      10968: # Store
                   10969:           my ($username,$domain)=split(/\:/,$user);
                   10970:           my %grades=();
                   10971:           $grades{"resource.$part.solved"}='correct_by_override';
                   10972:           $grades{"resource.$part.awarded"}=$ave;
                   10973:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10974:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10975:                                                  $env{'request.course.id'},
                   10976:                                                  $domain,$username);
                   10977:           if ($returncode ne 'ok') {
                   10978:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10979:           } else {
                   10980:              $storecount++;
                   10981:           }
1.415     www      10982:        }
                   10983:     }
                   10984: # We are done
1.549     hauer    10985:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10986:              '</td>'.
                   10987:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 10988:0):              &Apache::loncommon::end_data_table();
                   10989:0):     return $result;
1.414     www      10990: }
                   10991: 
1.582     raeburn  10992: sub navmap_errormsg {
                   10993:     return '<div class="LC_error">'.
                   10994:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10995:            &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  10996:            '</div>';
                   10997: }
                   10998: 
1.596.2.12.2.  (raeburn 10999:): sub startpage {
          5(raebur 11000:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 11001:9):     my %args;
                   11002:9):     if ($onload) {
                   11003:9):          my %loaditems = (
                   11004:9):                         'onload' => $onload,
                   11005:9):                       );
                   11006:9):          $args{'add_entries'} = \%loaditems;
                   11007:9):     }
          (raeburn 11008:):     if ($nomenu) {
          9(raebur 11009:9):         $args{'only_body'} = 1;
          5(raebur 11010:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 11011:):     } else {
          8(raebur 11012:1):         if ($env{'request.course.id'}) {
                   11013:1):             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   11014:1):         }
          9(raebur 11015:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 11016:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 11017:):     }
                   11018:):     unless ($nodisplayflag) {
          1(raebur 11019:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 11020:):     }
                   11021:): }
                   11022:): 
          1(raebur 11023:0): sub select_problem {
                   11024:0):     my ($r)=@_;
                   11025:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   11026:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   11027:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11028:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11029:0): }
                   11030:0): 
1.1       albertel 11031: sub handler {
1.41      ng       11032:     my $request=$_[0];
1.434     albertel 11033:     &reset_caches();
1.596.2.4  raeburn  11034:     if ($request->header_only) {
                   11035:         &Apache::loncommon::content_type($request,'text/html');
                   11036:         $request->send_http_header;
                   11037:         return OK;
1.41      ng       11038:     }
                   11039:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  11040: 
1.596.2.12.2.  1(raebur 11041:0): # see what command we need to execute
                   11042:0):  
1.160     albertel 11043:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11044:     my $command=$commands[0];
1.447     foxr     11045: 
1.596.2.12.2.  1(raebur 11046:0):     &init_perm();
                   11047:0):     if (!$env{'request.course.id'}) {
                   11048:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11049:0):                 ($command =~ /^scantronupload/)) {
                   11050:0):             # Not in a course.
                   11051:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11052:0):             return HTTP_NOT_ACCEPTABLE;
                   11053:0):         }
                   11054:0):     } elsif (!%perm) {
                   11055:0):         $request->internal_redirect('/adm/quickgrades');
                   11056:0):         return OK;
                   11057:0):     }
                   11058:0):     &Apache::loncommon::content_type($request,'text/html');
                   11059:0):     $request->send_http_header;
                   11060:0): 
1.160     albertel 11061:     if ($#commands > 0) {
                   11062: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11063:     }
1.447     foxr     11064: 
1.596.2.12.2.  1(raebur 11065:0): # see what the symb is
                   11066:0): 
                   11067:0):     my $symb=$env{'form.symb'};
                   11068:0):     unless ($symb) {
                   11069:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11070:0):        $symb=&Apache::lonnet::symbread($url);
                   11071:0):     }
                   11072:0):     &Apache::lonenc::check_decrypt(\$symb);
                   11073:0): 
1.513     foxr     11074:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 11075:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   11076:0): #
                   11077:0): # Not called from a resource, but inside a course
                   11078:0): #
                   11079:0):         &startpage($request,undef,[],1,1);
                   11080:0):         &select_problem($request);
1.41      ng       11081:     } else {
1.596.2.12.2.  1(raebur 11082:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   11083:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 11084:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11085:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11086:):                     &choose_task_version_form($symb,$env{'form.student'},
                   11087:):                                               $env{'form.userdom'});
                   11088:):             }
          1(raebur 11089:0):             my $divforres;
                   11090:0):             if ($env{'form.student'} eq '') {
                   11091:0):                 $js .= &part_selector_js();
                   11092:0):                 $onload = "toggleParts('gradesub');";
                   11093:0):             } else {
                   11094:0):                 $divforres = 1;
                   11095:0):             }
          5(raebur 11096:0):             my $head_extra = $js;
                   11097:0):             unless ($env{'form.vProb'} eq 'no') {
                   11098:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11099:0):                 if ($csslinks) {
                   11100:0):                     $head_extra .= "\n$csslinks";
                   11101:0):                 }
                   11102:0):             }
                   11103:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11104:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 11105:):             if ($versionform) {
          2(raebur 11106:0):                 if ($divforres) {
                   11107:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11108:0):                 }
          (raeburn 11109:):                 $request->print($versionform);
                   11110:):             }
          1(raebur 11111:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 11112:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11113:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11114:):                 &choose_task_version_form($symb,$env{'form.student'},
                   11115:):                                           $env{'form.userdom'},
                   11116:):                                           $env{'form.inhibitmenu'});
          5(raebur 11117:0):             my $head_extra = $js;
                   11118:0):             unless ($env{'form.vProb'} eq 'no') {
                   11119:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11120:0):                 if ($csslinks) {
                   11121:0):                     $head_extra .= "\n$csslinks";
                   11122:0):                 }
                   11123:0):             }
                   11124:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11125:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 11126:):             if ($versionform) {
                   11127:):                 $request->print($versionform);
                   11128:):             }
                   11129:):             $request->print('<br clear="all" />');
                   11130:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 11131:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   11132:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11133:0):                                        {href=>'',text=>'Select student'}],1,1);
                   11134:0):             &pickStudentPage($request,$symb);
                   11135:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 11136:0):             my $csslinks;
                   11137:0):             unless ($env{'form.vProb'} eq 'no') {
                   11138:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   11139:0):             }
          1(raebur 11140:0):             &startpage($request,$symb,
                   11141:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11142:0):                                        {href=>'',text=>'Select student'},
          5(raebur 11143:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 11144:0):             &displayPage($request,$symb);
                   11145:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   11146:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11147:0):                                        {href=>'',text=>'Select student'},
                   11148:0):                                        {href=>'',text=>'Grade student'},
                   11149:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   11150:0):             &updateGradeByPage($request,$symb);
                   11151:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 11152:0):             my $csslinks;
                   11153:0):             unless ($env{'form.vProb'} eq 'no') {
                   11154:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   11155:0):             }
          1(raebur 11156:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 11157:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 11158:0):             &processGroup($request,$symb);
                   11159:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11160:0):             &startpage($request,$symb);
                   11161:0):             $request->print(&grading_menu($request,$symb));
                   11162:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11163:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11164:0):             $request->print(&submit_options($request,$symb));
                   11165:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11166:0):             my $js = &part_selector_js();
                   11167:0):             my $onload = "toggleParts('gradesub');";
                   11168:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11169:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11170:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11171:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11172:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11173:0):             $request->print(&submit_options_table($request,$symb));
                   11174:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11175:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11176:0):             $request->print(&submit_options_sequence($request,$symb));
                   11177:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11178:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11179:0):             $request->print(&viewgrades($request,$symb));
                   11180:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11181:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11182:0):                                        {href=>'',text=>'Store grades'}]);
                   11183:0):             $request->print(&processHandGrade($request,$symb));
                   11184:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11185:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11186:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11187:0):                                                                              text=>"Modify grades"},
                   11188:0):                                        {href=>'', text=>"Store grades"}]);
                   11189:0):             $request->print(&editgrades($request,$symb));
                   11190:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11191:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11192:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11193:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11194:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11195:0):                                        {href=>'',text=>'Verification Result'}]);
                   11196:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11197:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11198:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11199:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11200:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11201:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11202:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11203:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11204:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11205:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11206:0):                                        {href=>'', text=>'Process clicker file'},
                   11207:0):                                        {href=>'', text=>'Store grades'}]);
                   11208:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11209:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11210:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11211:0):             $request->print(&upcsvScores_form($request,$symb));
                   11212:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11213:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11214:0):             $request->print(&csvupload($request,$symb));
                   11215:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11216:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11217:0):             $request->print(&csvuploadmap($request,$symb));
                   11218:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11219:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11220:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11221:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11222:0):             } else {
                   11223:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11224:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11225:0):                 } else {
                   11226:0):                     $env{'form.upfile_associate'} = 'forward';
                   11227:0):                 }
                   11228:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11229:0):                 $request->print(&csvuploadmap($request,$symb));
                   11230:0):             }
                   11231:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11232:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11233:0):             $request->print(&csvuploadassign($request,$symb));
                   11234:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11235:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11236:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11237:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11238:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11239:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11240:0):             $request->print(&scantron_do_warning($request,$symb));
                   11241:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11242:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11243:0):             $request->print(&scantron_validate_file($request,$symb));
                   11244:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11245:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11246:0):             $request->print(&scantron_process_students($request,$symb));
                   11247:0):         } elsif ($command eq 'scantronupload' &&
                   11248:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11249:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11250:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11251:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11252:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11253:0):         } elsif ($command eq 'scantronupload_save' &&
                   11254:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11255:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11256:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11257:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11258:0):         } elsif ($command eq 'scantron_download' &&
                   11259:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11260:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11261:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11262:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11263:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11264:0):             $request->print(&checkscantron_results($request,$symb));
                   11265:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11266:0):             my $js = &part_selector_js();
                   11267:0):             my $onload = "toggleParts('gradingMenu');";
                   11268:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11269:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11270:0):             $request->print(&submit_options_download($request,$symb));
                   11271:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11272:0):             &startpage($request,$symb,
                   11273:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11274:0):     {href=>'', text=>'Download submitted files'}],
                   11275:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11276:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11277:0):             &submit_download_link($request,$symb);
                   11278:0):         } elsif ($command) {
                   11279:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11280:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11281:0):         }
1.2       albertel 11282:     }
1.513     foxr     11283:     if ($ssi_error) {
                   11284: 	&ssi_print_error($request);
                   11285:     }
1.353     albertel 11286:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11287:     &reset_caches();
1.596.2.4  raeburn  11288:     return OK;
1.44      ng       11289: }
                   11290: 
1.1       albertel 11291: 1;
                   11292: 
1.13      albertel 11293: __END__;
1.531     jms      11294: 
                   11295: 
                   11296: =head1 NAME
                   11297: 
                   11298: Apache::grades
                   11299: 
                   11300: =head1 SYNOPSIS
                   11301: 
                   11302: Handles the viewing of grades.
                   11303: 
                   11304: This is part of the LearningOnline Network with CAPA project
                   11305: described at http://www.lon-capa.org.
                   11306: 
                   11307: =head1 OVERVIEW
                   11308: 
                   11309: Do an ssi with retries:
                   11310: While I'd love to factor out this with the vesrion in lonprintout,
                   11311: 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
                   11312: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11313: 
                   11314: At least the logic that drives this has been pulled out into loncommon.
                   11315: 
                   11316: 
                   11317: 
                   11318: ssi_with_retries - Does the server side include of a resource.
                   11319:                      if the ssi call returns an error we'll retry it up to
                   11320:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11321:4):                      If we still have a problem, no text is appended to the
1.531     jms      11322:                      output and we set some global variables.
                   11323:                      to indicate to the caller an SSI error occurred.  
                   11324:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11325:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11326:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11327:                      by informing the user that this happened.
                   11328: 
                   11329: Parameters:
                   11330:   resource   - The resource to include.  This is passed directly, without
                   11331:                interpretation to lonnet::ssi.
                   11332:   form       - The form hash parameters that guide the interpretation of the resource
                   11333:                
                   11334:   retries    - Number of retries allowed before giving up completely.
                   11335: Returns:
                   11336:   On success, returns the rendered resource identified by the resource parameter.
                   11337: Side Effects:
                   11338:   The following global variables can be set:
                   11339:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11340:                               It is up to the caller to initialize this to false
                   11341:                               if desired.
                   11342:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11343:                               of the resource that could not be rendered by the ssi
                   11344:                               call.
                   11345:    ssi_error_message   - The error string fetched from the ssi response
                   11346:                               in the event of an error.
                   11347: 
                   11348: 
                   11349: =head1 HANDLER SUBROUTINE
                   11350: 
                   11351: ssi_with_retries()
                   11352: 
                   11353: =head1 SUBROUTINES
                   11354: 
                   11355: =over
                   11356: 
                   11357: =item scantron_get_correction() : 
                   11358: 
                   11359:    Builds the interface screen to interact with the operator to fix a
                   11360:    specific error condition in a specific scanline
                   11361: 
                   11362:  Arguments:
                   11363:     $r           - Apache request object
                   11364:     $i           - number of the current scanline
                   11365:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11366:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11367:     $line        - full contents of the current scanline
                   11368:     $error       - error condition, valid values are
                   11369:                    'incorrectCODE', 'duplicateCODE',
                   11370:                    'doublebubble', 'missingbubble',
                   11371:                    'duplicateID', 'incorrectID'
                   11372:     $arg         - extra information needed
                   11373:        For errors:
                   11374:          - duplicateID   - paper number that this studentID was seen before on
                   11375:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11376:                            seen on before
                   11377:          - incorrectCODE - current incorrect CODE 
                   11378:          - doublebubble  - array ref of the bubble lines that have double
                   11379:                            bubble errors
                   11380:          - missingbubble - array ref of the bubble lines that have missing
                   11381:                            bubble errors
                   11382: 
1.596.2.12.2.  0(raebur 11383:2):    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11384:2):    $randompick  - True if exam folder (or a sub-folder) has randompick set
          6(raebur 11385:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11386:3):                      for current line to question number used for same question
                   11387:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11388:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11389:3):                   and value is number of first bubble line for current student
                   11390:3):                   or code-based randompick and/or randomorder.
                   11391:3): 
                   11392:3): 
1.531     jms      11393: =item  scantron_get_maxbubble() : 
                   11394: 
1.582     raeburn  11395:    Arguments:
                   11396:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11397:                       failure to retrieve a navmap object.
                   11398:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11399:        calling routine should trap the error condition and display the warning
                   11400:        found in &navmap_errormsg().
                   11401: 
1.596.2.12.2.  (raeburn 11402:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11403:): 
1.531     jms      11404:    Returns the maximum number of bubble lines that are expected to
                   11405:    occur. Does this by walking the selected sequence rendering the
                   11406:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11407:    for what the current value of the problem counter is.
                   11408: 
                   11409:    Caches the results to $env{'form.scantron_maxbubble'},
                   11410:    $env{'form.scantron.bubble_lines.n'}, 
                   11411:    $env{'form.scantron.first_bubble_line.n'} and
                   11412:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11413:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11414:    lines for response n and number of the first bubble line for response n,
                   11415:    and a comma separated list of numbers of bubble lines for sub-questions
                   11416:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11417: 
                   11418: 
                   11419: =item  scantron_validate_missingbubbles() : 
                   11420: 
                   11421:    Validates all scanlines in the selected file to not have any
                   11422:     answers that don't have bubbles that have not been verified
                   11423:     to be bubble free.
                   11424: 
                   11425: =item  scantron_process_students() : 
                   11426: 
1.596.2.6  raeburn  11427:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11428: 
                   11429:    The parsed scanline hash is added to %env 
                   11430: 
                   11431:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11432:    foreach resource , with the form data of
                   11433: 
                   11434: 	'submitted'     =>'scantron' 
                   11435: 	'grade_target'  =>'grade',
                   11436: 	'grade_username'=> username of student
                   11437: 	'grade_domain'  => domain of student
                   11438: 	'grade_courseid'=> of course
                   11439: 	'grade_symb'    => symb of resource to grade
                   11440: 
                   11441:     This triggers a grading pass. The problem grading code takes care
                   11442:     of converting the bubbled letter information (now in %env) into a
                   11443:     valid submission.
                   11444: 
                   11445: =item  scantron_upload_scantron_data() :
                   11446: 
1.596.2.6  raeburn  11447:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11448: 
                   11449: =item  scantron_upload_scantron_data_save() : 
                   11450: 
                   11451:    Adds a provided bubble information data file to the course if user
                   11452:    has the correct privileges to do so. 
                   11453: 
                   11454: =item  valid_file() :
                   11455: 
                   11456:    Validates that the requested bubble data file exists in the course.
                   11457: 
                   11458: =item  scantron_download_scantron_data() : 
                   11459: 
                   11460:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11461:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11462:    course.
                   11463: 
                   11464: =item  scantron_validate_ID() : 
                   11465: 
                   11466:    Validates all scanlines in the selected file to not have any
1.556     weissno  11467:    invalid or underspecified student/employee IDs
1.531     jms      11468: 
1.582     raeburn  11469: =item navmap_errormsg() :
                   11470: 
                   11471:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11472:    Should be called whenever the request to instantiate a navmap object fails.  
                   11473: 
1.531     jms      11474: =back
                   11475: 
                   11476: =cut

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