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

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.  6(raebur    4:1): # $Id: grades.pm,v 1.596.2.12.2.55 2020/11/12 01:37:12 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'});
                   1153:1):         } else {
                   1154:1):             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1155:1):         }
                   1156:1):         if (grep(/^all$/,@sections)) {
                   1157:1):             $showmore = 1;
                   1158:1):         } else {
                   1159:1):             foreach my $sec (@sections) {
                   1160:1):                 if (&canmodify($sec)) {
                   1161:1):                     $showmore = 1;
                   1162:1):                     last;
                   1163:1):                 }
                   1164:1):             }
                   1165:1):         }
                   1166:1):     }
                   1167:1): 
                   1168:1):     if ($showmore) {
                   1169:1):         $gradeTable .=
                   1170:1):                    &Apache::lonhtmlcommon::row_closure()
          1(raebur 1171:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1172:0):                   .'<span class="LC_nobreak">'
                   1173:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1174:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1175:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1176:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1177:                   .&Apache::lonhtmlcommon::row_closure();
                   1178: 
1.596.2.12.2.  6(raebur 1179:1):         $gradeTable .= 
                   1180:1):                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1181:                   .'<select name="increment">'
                   1182:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1183:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1184:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1185:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1186:0):                   .'</select>';
          6(raebur 1187:1):     }
1.485     albertel 1188:     $gradeTable .= 
1.432     banghart 1189:         &build_section_inputs().
1.45      ng       1190: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1191: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1192: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1193:0):     if (exists($env{'form.Status'})) {
1.561     bisitz   1194: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1195:     } else {
1.596.2.12.2.  1(raebur 1196:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1197:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1198:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1199:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1200:     }
1.596.2.12.2.  1(raebur 1201:0):     if ($numessay) {
                   1202:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1203:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1204:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1205:0):     }
                   1206:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1207:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1208: 
                   1209:     $gradeTable .= '<p>'
1.596.2.12.2.  1(raebur 1210: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   1211:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1212:                   .'</p>';
1.249     albertel 1213: 
                   1214: # checkall buttons
                   1215:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1216:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1217:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1218:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1219:     $gradeTable.=&check_buttons();
1.450     banghart 1220:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1221:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1222: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1223:     my $loop = 0;
                   1224:     while ($loop < 2) {
1.485     albertel 1225: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1226: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1227:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1228: 	    foreach my $part (sort(@$partlist)) {
                   1229: 		my $display_part=
                   1230: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1231: 		$gradeTable.=
                   1232: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1233: 	    }
1.301     albertel 1234: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1235: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1236: 	}
                   1237: 	$loop++;
1.126     ng       1238: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1239:     }
1.474     albertel 1240:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1241: 
1.45      ng       1242:     my $ctr = 0;
1.294     albertel 1243:     foreach my $student (sort 
                   1244: 			 {
                   1245: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1246: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1247: 			     }
                   1248: 			     return $a cmp $b;
                   1249: 			 }
                   1250: 			 (keys(%$fullname))) {
1.41      ng       1251: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1252: 
1.110     ng       1253: 	my %status = ();
1.301     albertel 1254: 
                   1255: 	if ($submitonly eq 'queued') {
                   1256: 	    my %queue_status = 
                   1257: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1258: 							$udom,$uname);
                   1259: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1260: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1261: 	}
                   1262: 
1.596.2.12.2.  1(raebur 1263:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1264: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1265: 	    my $submitted = 0;
1.164     albertel 1266: 	    my $graded = 0;
1.248     albertel 1267: 	    my $incorrect = 0;
1.110     ng       1268: 	    foreach (keys(%status)) {
1.145     albertel 1269: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1270: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1271: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1272: 		
1.110     ng       1273: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1274: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1275: 		    $submitted = 0;
1.150     albertel 1276: 		    my ($part)=split(/\./,$partid);
1.110     ng       1277: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1278: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1279: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1280: 		}
1.41      ng       1281: 	    }
1.248     albertel 1282: 	    
1.156     albertel 1283: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1284: 				     $submitonly eq 'incorrect' ||
                   1285: 				     $submitonly eq 'graded'));
1.248     albertel 1286: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1287: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1288: 	}
1.34      ng       1289: 
1.45      ng       1290: 	$ctr++;
1.249     albertel 1291: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1292:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1293: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1294: 	    if ($ctr%2 ==1) {
                   1295: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1296: 	    }
1.126     ng       1297: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1298:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1299:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1300: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1301: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1302: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1303: 
1.596.2.12.2.  1(raebur 1304:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1305: 		foreach (sort(keys(%status))) {
1.485     albertel 1306: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1307: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1308: 		}
1.41      ng       1309: 	    }
1.126     ng       1310: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1311: 	    if ($ctr%2 ==0) {
                   1312: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1313: 	    }
1.41      ng       1314: 	}
                   1315:     }
1.110     ng       1316:     if ($ctr%2 ==1) {
1.126     ng       1317: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1318:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1319: 		foreach (@$partlist) {
                   1320: 		    $gradeTable.='<td>&nbsp;</td>';
                   1321: 		}
1.301     albertel 1322: 	    } elsif ($submitonly eq 'queued') {
                   1323: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1324: 	    }
1.474     albertel 1325: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1326:     }
                   1327: 
1.474     albertel 1328:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1329:         '<input type="button" '.
                   1330:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1331:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1332:     if ($ctr == 0) {
1.96      albertel 1333: 	my $num_students=(scalar(keys(%$fullname)));
                   1334: 	if ($num_students eq 0) {
1.485     albertel 1335: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1336: 	} else {
1.171     albertel 1337: 	    my $submissions='submissions';
                   1338: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1339: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1340: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1341: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1342:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1343: 		    $num_students).
                   1344: 		'</span><br />';
1.96      albertel 1345: 	}
1.46      ng       1346:     } elsif ($ctr == 1) {
1.474     albertel 1347: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1348:     }
                   1349:     $request->print($gradeTable);
1.44      ng       1350:     return '';
1.10      ng       1351: }
                   1352: 
1.44      ng       1353: #---- Called from the listStudents routine
1.249     albertel 1354: 
                   1355: sub check_script {
1.596.2.12.2.  1(raebur 1356:0):     my ($form,$type) = @_;
                   1357:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1358:     function checkall() {
                   1359:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1360:             ele = document.forms.'.$form.'.elements[i];
                   1361:             if (ele.name == "'.$type.'") {
                   1362:             document.forms.'.$form.'.elements[i].checked=true;
                   1363:                                        }
                   1364:         }
                   1365:     }
                   1366: 
                   1367:     function checksec() {
                   1368:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1369:             ele = document.forms.'.$form.'.elements[i];
                   1370:            string = document.forms.'.$form.'.chksec.value;
                   1371:            if
                   1372:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1373:               document.forms.'.$form.'.elements[i].checked=true;
                   1374:             }
                   1375:         }
                   1376:     }
                   1377: 
                   1378: 
                   1379:     function uncheckall() {
                   1380:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1381:             ele = document.forms.'.$form.'.elements[i];
                   1382:             if (ele.name == "'.$type.'") {
                   1383:             document.forms.'.$form.'.elements[i].checked=false;
                   1384:                                        }
                   1385:         }
                   1386:     }
                   1387: 
1.596.2.12.2.  1(raebur 1388:0): '."\n");
1.249     albertel 1389:     return $chkallscript;
                   1390: }
                   1391: 
                   1392: sub check_buttons {
1.485     albertel 1393:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1394:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1395:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1396:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1397:     return $buttons;
                   1398: }
                   1399: 
1.44      ng       1400: #     Displays the submissions for one student or a group of students
1.34      ng       1401: sub processGroup {
1.596.2.12.2.  1(raebur 1402:0):     my ($request,$symb) = @_;
1.41      ng       1403:     my $ctr        = 0;
1.155     albertel 1404:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1405:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1406: 
1.396     banghart 1407:     foreach my $student (@stuchecked) {
                   1408: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1409: 	$env{'form.student'}        = $uname;
                   1410: 	$env{'form.userdom'}        = $udom;
                   1411: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1412:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1413: 	$ctr++;
                   1414:     }
                   1415:     return '';
1.35      ng       1416: }
1.34      ng       1417: 
1.44      ng       1418: #------------------------------------------------------------------------------------
                   1419: #
                   1420: #-------------------------- Next few routines handles grading by student, essentially
                   1421: #                           handles essay response type problem/part
                   1422: #
                   1423: #--- Javascript to handle the submission page functionality ---
                   1424: sub sub_page_js {
                   1425:     my $request = shift;
1.596.2.12.2.  6(raebur 1426:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1427:6):     &js_escape(\$alertmsg);
          1(raebur 1428:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1429:     function updateRadio(formname,id,weight) {
1.125     ng       1430: 	var gradeBox = formname["GD_BOX"+id];
                   1431: 	var radioButton = formname["RADVAL"+id];
                   1432: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1433: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1434: 	gradeBox.value = pts;
                   1435: 	var resetbox = false;
                   1436: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1437: 	    alert("$alertmsg"+pts);
1.71      ng       1438: 	    for (var i=0; i<radioButton.length; i++) {
                   1439: 		if (radioButton[i].checked) {
                   1440: 		    gradeBox.value = i;
                   1441: 		    resetbox = true;
                   1442: 		}
                   1443: 	    }
                   1444: 	    if (!resetbox) {
                   1445: 		formtextbox.value = "";
                   1446: 	    }
                   1447: 	    return;
1.44      ng       1448: 	}
1.71      ng       1449: 
                   1450: 	if (pts > weight) {
                   1451: 	    var resp = confirm("You entered a value ("+pts+
                   1452: 			       ") greater than the weight for the part. Accept?");
                   1453: 	    if (resp == false) {
1.125     ng       1454: 		gradeBox.value = oldpts;
1.71      ng       1455: 		return;
                   1456: 	    }
1.44      ng       1457: 	}
1.13      albertel 1458: 
1.71      ng       1459: 	for (var i=0; i<radioButton.length; i++) {
                   1460: 	    radioButton[i].checked=false;
                   1461: 	    if (pts == i && pts != "") {
                   1462: 		radioButton[i].checked=true;
                   1463: 	    }
                   1464: 	}
                   1465: 	updateSelect(formname,id);
1.125     ng       1466: 	formname["stores"+id].value = "0";
1.41      ng       1467:     }
1.5       albertel 1468: 
1.72      ng       1469:     function writeBox(formname,id,pts) {
1.125     ng       1470: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1471: 	if (checkSolved(formname,id) == 'update') {
                   1472: 	    gradeBox.value = pts;
                   1473: 	} else {
1.125     ng       1474: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1475: 	    gradeBox.value = oldpts;
1.125     ng       1476: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1477: 	    for (var i=0; i<radioButton.length; i++) {
                   1478: 		radioButton[i].checked=false;
1.72      ng       1479: 		if (i == oldpts) {
1.71      ng       1480: 		    radioButton[i].checked=true;
                   1481: 		}
                   1482: 	    }
1.41      ng       1483: 	}
1.125     ng       1484: 	formname["stores"+id].value = "0";
1.71      ng       1485: 	updateSelect(formname,id);
                   1486: 	return;
1.41      ng       1487:     }
1.44      ng       1488: 
1.71      ng       1489:     function clearRadBox(formname,id) {
                   1490: 	if (checkSolved(formname,id) == 'noupdate') {
                   1491: 	    updateSelect(formname,id);
                   1492: 	    return;
                   1493: 	}
1.125     ng       1494: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1495: 	for (var i=0; i<gradeSelect.length; i++) {
                   1496: 	    if (gradeSelect[i].selected) {
                   1497: 		var selectx=i;
                   1498: 	    }
                   1499: 	}
1.125     ng       1500: 	var stores = formname["stores"+id];
1.71      ng       1501: 	if (selectx == stores.value) { return };
1.125     ng       1502: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1503: 	gradeBox.value = "";
1.125     ng       1504: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1505: 	for (var i=0; i<radioButton.length; i++) {
                   1506: 	    radioButton[i].checked=false;
                   1507: 	}
                   1508: 	stores.value = selectx;
                   1509:     }
1.5       albertel 1510: 
1.71      ng       1511:     function checkSolved(formname,id) {
1.125     ng       1512: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1513: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1514: 	    if (!reply) {return "noupdate";}
1.120     ng       1515: 	    formname.overRideScore.value = 'yes';
1.41      ng       1516: 	}
1.71      ng       1517: 	return "update";
1.13      albertel 1518:     }
1.71      ng       1519: 
                   1520:     function updateSelect(formname,id) {
1.125     ng       1521: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1522: 	return;
1.41      ng       1523:     }
1.33      ng       1524: 
1.121     ng       1525: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1526:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1527: 	formname.gradeOpt.value = val;
1.71      ng       1528: 	if (val == "Save & Next") {
                   1529: 	    for (i=0;i<=total;i++) {
                   1530: 		for (j=0;j<parttot;j++) {
1.125     ng       1531: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1532: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1533: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1534: 			if (points == "") {
1.125     ng       1535: 			    var name = formname["name"+i].value;
1.129     ng       1536: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1537: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1538: 					       ", part "+partid+". Continue?");
1.71      ng       1539: 			    if (resp == false) {
1.125     ng       1540: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1541: 				return false;
                   1542: 			    }
                   1543: 			}
                   1544: 		    }
                   1545: 		}
                   1546: 	    }
                   1547: 	}
1.120     ng       1548: 	formname.submit();
                   1549:     }
                   1550: 
1.71      ng       1551: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1552:     function checkSubmitPage(formname,total) {
                   1553: 	noscore = new Array(100);
                   1554: 	var ptr = 0;
                   1555: 	for (i=1;i<total;i++) {
1.125     ng       1556: 	    var partid = formname["q_"+i].value;
1.127     ng       1557: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1558: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1559: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1560: 		if (points == "" && status != "correct_by_student") {
                   1561: 		    noscore[ptr] = i;
                   1562: 		    ptr++;
                   1563: 		}
                   1564: 	    }
                   1565: 	}
                   1566: 	if (ptr != 0) {
                   1567: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1568: 	    var prolist = "";
                   1569: 	    if (ptr == 1) {
                   1570: 		prolist = noscore[0];
                   1571: 	    } else {
                   1572: 		var i = 0;
                   1573: 		while (i < ptr-1) {
                   1574: 		    prolist += noscore[i]+", ";
                   1575: 		    i++;
                   1576: 		}
                   1577: 		prolist += "and "+noscore[i];
                   1578: 	    }
                   1579: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1580: 	    if (resp == false) {
                   1581: 		return false;
                   1582: 	    }
                   1583: 	}
1.45      ng       1584: 
1.71      ng       1585: 	formname.submit();
                   1586:     }
                   1587: SUBJAVASCRIPT
                   1588: }
1.45      ng       1589: 
1.596.2.12.2.  1(raebur 1590:0): #--- javascript for grading message center
                   1591:0): sub sub_grademessage_js {
1.71      ng       1592:     my $request = shift;
1.80      ng       1593:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1594:     &commonJSfunctions($request);
1.350     albertel 1595: 
1.596.2.12.2.  1(raebur 1596:0):     my $inner_js_msg_central= (<<INNERJS);
                   1597:0): <script type="text/javascript">
1.350     albertel 1598:     function checkInput() {
                   1599:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1600:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1601:       var usrctr = document.msgcenter.usrctr.value;
                   1602:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1603:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1604: 
                   1605:       var msgchk = "";
                   1606:       if (document.msgcenter.subchk.checked) {
                   1607:          msgchk = "msgsub,";
                   1608:       }
                   1609:       var includemsg = 0;
                   1610:       for (var i=1; i<=nmsg; i++) {
                   1611:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1612:           var frmmsg = document.msgcenter["msg"+i];
                   1613:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1614:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1615:           showflg.value = "1";
                   1616:           var chkbox = document.msgcenter["msgn"+i];
                   1617:           if (chkbox.checked) {
                   1618:              msgchk += "savemsg"+i+",";
                   1619:              includemsg = 1;
                   1620:           }
                   1621:       }
                   1622:       if (document.msgcenter.newmsgchk.checked) {
                   1623:          msgchk += "newmsg"+usrctr;
                   1624:          includemsg = 1;
                   1625:       }
                   1626:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1627:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1628:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1629:       includemsg.value = msgchk;
                   1630: 
                   1631:       self.close()
                   1632: 
                   1633:     }
1.351     albertel 1634: </script>
                   1635: INNERJS
                   1636: 
1.596.2.12.2.  1(raebur 1637:0):     my $start_page_msg_central =
1.351     albertel 1638:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1639: 				       {'js_ready'  => 1,
                   1640: 					'only_body' => 1,
                   1641: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1642:0):     my $end_page_msg_central =
1.351     albertel 1643: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1644: 
                   1645: 
1.219     www      1646:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1647:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1648:0): 
          6(raebur 1649:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1650:                 comp => 'Compose Message for: ',
                   1651:                 incl => 'Include',
                   1652:                 type => 'Type',
                   1653:                 subj => 'Subject',
                   1654:                 mesa => 'Message',
                   1655:                 new  => 'New',
                   1656:                 save => 'Save',
                   1657:                 canc => 'Cancel',
                   1658:              );
1.596.2.12.2.  6(raebur 1659:6):     &html_escape(\%html_js_lt);
                   1660:6):     &js_escape(\%html_js_lt);
          1(raebur 1661:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1662: 
                   1663: //===================== Script to view submitted by ==================
                   1664:   function viewSubmitter(submitter) {
                   1665:     document.SCORE.refresh.value = "on";
                   1666:     document.SCORE.NCT.value = "1";
                   1667:     document.SCORE.unamedom0.value = submitter;
                   1668:     document.SCORE.submit();
                   1669:     return;
                   1670:   }
                   1671: 
                   1672: //====================== Script for composing message ==============
1.80      ng       1673:    // preload images
                   1674:    img1 = new Image();
                   1675:    img1.src = "$iconpath/mailbkgrd.gif";
                   1676:    img2 = new Image();
                   1677:    img2.src = "$iconpath/mailto.gif";
                   1678: 
1.44      ng       1679:   function msgCenter(msgform,usrctr,fullname) {
                   1680:     var Nmsg  = msgform.savemsgN.value;
                   1681:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1682:     var subject = msgform.msgsub.value;
1.127     ng       1683:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1684:     re = /msgsub/;
                   1685:     var shwsel = "";
                   1686:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1687:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1688:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1689:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1690: 	var testmsg = "savemsg"+i+",";
                   1691: 	re = new RegExp(testmsg,"g");
1.44      ng       1692: 	shwsel = "";
                   1693: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1694: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1695: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1696: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1697: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1698:     }
1.125     ng       1699:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1700:     shwsel = "";
                   1701:     re = /newmsg/;
                   1702:     if (re.test(msgchk)) { shwsel = "checked" }
                   1703:     newMsg(newmsg,shwsel);
                   1704:     msgTail(); 
                   1705:     return;
                   1706:   }
                   1707: 
1.123     ng       1708:   function checkEntities(strx) {
                   1709:     if (strx.length == 0) return strx;
                   1710:     var orgStr = ["&", "<", ">", '"']; 
                   1711:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1712:     var counter = 0;
                   1713:     while (counter < 4) {
                   1714: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1715: 	counter++;
                   1716:     }
                   1717:     return strx;
                   1718:   }
                   1719: 
                   1720:   function strReplace(strx, orgStr, newStr) {
                   1721:     return strx.split(orgStr).join(newStr);
                   1722:   }
                   1723: 
1.44      ng       1724:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1725:     var height = 70*Nmsg+250;
1.44      ng       1726:     if (height > 600) {
                   1727: 	height = 600;
                   1728:     }
1.118     ng       1729:     var xpos = (screen.width-600)/2;
                   1730:     xpos = (xpos < 0) ? '0' : xpos;
                   1731:     var ypos = (screen.height-height)/2-30;
                   1732:     ypos = (ypos < 0) ? '0' : ypos;
                   1733: 
1.596.2.12.2.  (raeburn 1734:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1735:     pWin.focus();
                   1736:     pDoc = pWin.document;
1.219     www      1737:     pDoc.$docopen;
1.351     albertel 1738:     pDoc.write('$start_page_msg_central');
1.76      ng       1739: 
                   1740:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1741:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1742:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1743: 
1.596.2.12.2.  1(raebur 1744:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1745: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       1746: }
                   1747:     function displaySubject(msg,shwsel) {
1.76      ng       1748:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1749:0):     pDoc.write("<tr>");
1.465     albertel 1750:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1751:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1752:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1753: }
                   1754: 
1.72      ng       1755:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1756:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1757:0):     pDoc.write("<tr>");
1.465     albertel 1758:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1759:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1760:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1761: }
                   1762: 
                   1763:   function newMsg(newmsg,shwsel) {
1.76      ng       1764:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1765:0):     pDoc.write("<tr>");
1.465     albertel 1766:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1767:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1768:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1769: }
                   1770: 
                   1771:   function msgTail() {
1.76      ng       1772:     pDoc = pWin.document;
1.465     albertel 1773:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1774:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1775:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1776:     pDoc.write("<\\/form>");
1.351     albertel 1777:     pDoc.write('$end_page_msg_central');
1.128     ng       1778:     pDoc.close();
1.44      ng       1779: }
                   1780: 
1.596.2.12.2.  1(raebur 1781:0): SUBJAVASCRIPT
                   1782:0): }
                   1783:0): 
                   1784:0): #--- javascript for essay type problem --
                   1785:0): sub sub_page_kw_js {
                   1786:0):     my $request = shift;
                   1787:0): 
                   1788:0):     unless ($env{'form.compmsg'}) {
                   1789:0):         &commonJSfunctions($request);
                   1790:0):     }
                   1791:0): 
                   1792:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1793:0): <script type="text/javascript">
                   1794:0):     function updateChoice(flag) {
                   1795:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1796:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1797:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1798:0):       opener.document.SCORE.refresh.value = "on";
                   1799:0):       if (opener.document.SCORE.keywords.value!=""){
                   1800:0):          opener.document.SCORE.submit();
                   1801:0):       }
                   1802:0):       self.close()
                   1803:0):     }
                   1804:0): </script>
                   1805:0): INNERJS
                   1806:0): 
                   1807:0):     my $start_page_highlight_central =
                   1808:0):         &Apache::loncommon::start_page('Highlight Central',
                   1809:0):                                        $inner_js_highlight_central,
                   1810:0):                                        {'js_ready'  => 1,
                   1811:0):                                         'only_body' => 1,
                   1812:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1813:0):     my $end_page_highlight_central =
                   1814:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1815:0): 
                   1816:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1817:0):     $docopen=~s/^document\.//;
                   1818:0): 
                   1819:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1820:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1821:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1822:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1823:0):                 col1 => 'red',
                   1824:0):                 col2 => 'green',
                   1825:0):                 col3 => 'blue',
                   1826:0):                 siz1 => 'normal',
                   1827:0):                 siz2 => '+1',
                   1828:0):                 siz3 => '+2',
                   1829:0):                 sty1 => 'normal',
                   1830:0):                 sty2 => 'italic',
                   1831:0):                 sty3 => 'bold',
                   1832:0):              );
                   1833:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1834:0):                 save => 'Save',
                   1835:0):                 canc => 'Cancel',
                   1836:0):                 kehi => 'Keyword Highlight Options',
                   1837:0):                 txtc => 'Text Color',
                   1838:0):                 font => 'Font Size',
                   1839:0):                 fnst => 'Font Style',
                   1840:0):              );
                   1841:0):     &js_escape(\%js_lt);
                   1842:0):     &html_escape(\%html_js_lt);
                   1843:0):     &js_escape(\%html_js_lt);
                   1844:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1845:0): 
                   1846:0): //===================== Show list of keywords ====================
                   1847:0):   function keywords(formname) {
                   1848:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1849:0):     if (nret==null) return;
                   1850:0):     formname.keywords.value = nret;
                   1851:0): 
                   1852:0):     if (formname.keywords.value != "") {
                   1853:0):         formname.refresh.value = "on";
                   1854:0):         formname.submit();
                   1855:0):     }
                   1856:0):     return;
                   1857:0):   }
                   1858:0): 
                   1859:0): //===================== Script to add keyword(s) ==================
                   1860:0):   function getSel() {
                   1861:0):     if (document.getSelection) txt = document.getSelection();
                   1862:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1863:0):     else return;
                   1864:0):     if (typeof(txt) != 'string') {
                   1865:0):         txt = String(txt);
                   1866:0):     }
                   1867:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1868:0):     if (cleantxt=="") {
                   1869:0):         alert("$js_lt{'plse'}");
                   1870:0):         return;
                   1871:0):     }
                   1872:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1873:0):     if (nret==null) return;
                   1874:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1875:0):     if (document.SCORE.keywords.value != "") {
                   1876:0):         document.SCORE.refresh.value = "on";
                   1877:0):         document.SCORE.submit();
                   1878:0):     }
                   1879:0):     return;
                   1880:0):   }
                   1881:0): 
1.44      ng       1882: //====================== Script for keyword highlight options ==============
                   1883:   function kwhighlight() {
                   1884:     var kwclr    = document.SCORE.kwclr.value;
                   1885:     var kwsize   = document.SCORE.kwsize.value;
                   1886:     var kwstyle  = document.SCORE.kwstyle.value;
                   1887:     var redsel = "";
                   1888:     var grnsel = "";
                   1889:     var blusel = "";
1.596.2.12.2.  6(raebur 1890:6):     var txtcol1 = "$js_lt{'col1'}";
                   1891:6):     var txtcol2 = "$js_lt{'col2'}";
                   1892:6):     var txtcol3 = "$js_lt{'col3'}";
                   1893:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1894:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1895:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1896:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1897:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1898:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1899:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1900:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1901:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1902:     var sznsel = "";
                   1903:     var sz1sel = "";
                   1904:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1905:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1906:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1907:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1908:     var synsel = "";
                   1909:     var syisel = "";
                   1910:     var sybsel = "";
1.596.2.12.2.  8(raebur 1911:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1912:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1913:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1914:     highlightCentral();
1.596.2.12.2.  8(raebur 1915:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1916:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1917:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1918:     highlightend();
                   1919:     return;
                   1920:   }
                   1921: 
                   1922:   function highlightCentral() {
1.76      ng       1923: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1924:     var xpos = (screen.width-400)/2;
                   1925:     xpos = (xpos < 0) ? '0' : xpos;
                   1926:     var ypos = (screen.height-330)/2-30;
                   1927:     ypos = (ypos < 0) ? '0' : ypos;
                   1928: 
1.206     albertel 1929:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1930:     hwdWin.focus();
                   1931:     var hDoc = hwdWin.document;
1.219     www      1932:     hDoc.$docopen;
1.351     albertel 1933:     hDoc.write('$start_page_highlight_central');
1.76      ng       1934:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1935:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1936: 
1.596.2.12.2.  8(raebur 1937:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1938: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       1939:   }
                   1940: 
                   1941:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1942:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1943:4):     hDoc.write("<tr>");
1.76      ng       1944:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1945:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1946:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1947:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1948:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1949:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1950:     hDoc.write("<\\/tr>");
1.44      ng       1951:   }
                   1952: 
                   1953:   function highlightend() { 
1.76      ng       1954:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1955:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1956:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1957:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1958:     hDoc.write("<\\/form>");
1.351     albertel 1959:     hDoc.write('$end_page_highlight_central');
1.128     ng       1960:     hDoc.close();
1.44      ng       1961:   }
                   1962: 
                   1963: SUBJAVASCRIPT
                   1964: }
                   1965: 
1.349     albertel 1966: sub get_increment {
1.348     bowersj2 1967:     my $increment = $env{'form.increment'};
                   1968:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1969:         $increment != .1) {
                   1970:         $increment = 1;
                   1971:     }
                   1972:     return $increment;
                   1973: }
                   1974: 
1.585     bisitz   1975: sub gradeBox_start {
                   1976:     return (
                   1977:         &Apache::loncommon::start_data_table()
                   1978:        .&Apache::loncommon::start_data_table_header_row()
                   1979:        .'<th>'.&mt('Part').'</th>'
                   1980:        .'<th>'.&mt('Points').'</th>'
                   1981:        .'<th>&nbsp;</th>'
                   1982:        .'<th>'.&mt('Assign Grade').'</th>'
                   1983:        .'<th>'.&mt('Weight').'</th>'
                   1984:        .'<th>'.&mt('Grade Status').'</th>'
                   1985:        .&Apache::loncommon::end_data_table_header_row()
                   1986:     );
                   1987: }
                   1988: 
                   1989: sub gradeBox_end {
                   1990:     return (
                   1991:         &Apache::loncommon::end_data_table()
                   1992:     );
                   1993: }
1.71      ng       1994: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1995: sub gradeBox {
1.322     albertel 1996:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1997:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1998: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1999:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2000:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2001:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2002:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2003:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2004: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 2005:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2006:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2007:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2008: 				       [$partid]);
                   2009:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2010:     if ($last_resets{$partid}) {
                   2011:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2012:     }
1.596.2.12.2.  8(raebur 2013:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2014:     my $ctr = 0;
1.348     bowersj2 2015:     my $thisweight = 0;
1.349     albertel 2016:     my $increment = &get_increment();
1.485     albertel 2017: 
                   2018:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2019:     while ($thisweight<=$wgt) {
1.532     bisitz   2020: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2021:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2022: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2023: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2024: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2025:         $thisweight += $increment;
1.71      ng       2026: 	$ctr++;
                   2027:     }
1.485     albertel 2028:     $radio.='</tr></table>';
                   2029: 
                   2030:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2031: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2032: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2033: 	$wgt.')" /></td>'."\n";
1.485     albertel 2034:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2035: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2036: 	' </td>'."\n";
                   2037:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2038: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2039:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2040: 	$line.='<option></option>'.
                   2041: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2042:     } else {
1.485     albertel 2043: 	$line.='<option selected="selected"></option>'.
                   2044: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2045:     }
1.485     albertel 2046:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2047: 
                   2048: 
                   2049:     $result .= 
1.596.2.12.2.  8(raebur 2050:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2051:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2052:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2053:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2054: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2055: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2056: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2057:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2058:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2059:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2060:         $aggtries.'" />'."\n";
1.582     raeburn  2061:     my $res_error;
                   2062:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2063:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2064:     if ($res_error) {
                   2065:         return &navmap_errormsg();
                   2066:     }
1.318     banghart 2067:     return $result;
                   2068: }
1.322     albertel 2069: 
                   2070: sub handback_box {
1.596.2.12.2.  1(raebur 2071:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2072:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2073:0):     return unless ($numessay);
1.323     banghart 2074:     my (@respids);
1.596.2.4  raeburn  2075:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2076:     foreach my $part_response_id (@part_response_id) {
                   2077:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2078:         if ($part eq $partid) {
1.375     albertel 2079:             push(@respids,$resp);
1.323     banghart 2080:         }
                   2081:     }
1.318     banghart 2082:     my $result;
1.323     banghart 2083:     foreach my $respid (@respids) {
1.322     albertel 2084: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2085: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2086: 	next if (!@$files);
1.596.2.4  raeburn  2087: 	my $file_counter = 0;
1.313     banghart 2088: 	foreach my $file (@$files) {
1.368     banghart 2089: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2090:                 $file_counter++;
1.368     banghart 2091:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2092:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2093:     	        $file_disp = "$name.$ext";
                   2094:     	        $file = $file_path.$file_disp;
                   2095:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2096:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2097:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2098:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2099: 	    }
1.322     albertel 2100: 	}
1.596.2.4  raeburn  2101:         if ($file_counter) {
                   2102:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2103:                        '<span class="LC_info">'.
                   2104:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2105:         }
1.313     banghart 2106:     }
1.318     banghart 2107:     return $result;    
1.71      ng       2108: }
1.44      ng       2109: 
1.58      albertel 2110: sub show_problem {
1.382     albertel 2111:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2112:     my $rendered;
1.382     albertel 2113:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2114:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2115:     if ($mode eq 'both' or $mode eq 'text') {
                   2116: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2117: 						       $env{'request.course.id'},
                   2118: 						       undef,\%form);
1.144     albertel 2119:     }
1.58      albertel 2120:     if ($removeform) {
                   2121: 	$rendered=~s|<form(.*?)>||g;
                   2122: 	$rendered=~s|</form>||g;
1.374     albertel 2123: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2124:     }
1.144     albertel 2125:     my $companswer;
                   2126:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2127: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2128: 	$companswer=
                   2129: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2130: 						    $env{'request.course.id'},
                   2131: 						    %form);
1.144     albertel 2132:     }
1.58      albertel 2133:     if ($removeform) {
                   2134: 	$companswer=~s|<form(.*?)>||g;
                   2135: 	$companswer=~s|</form>||g;
1.144     albertel 2136: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2137:     }
1.596.2.12.2.  (raeburn 2138:):     my $renderheading = &mt('View of the problem');
                   2139:):     my $answerheading = &mt('Correct answer');
                   2140:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2141:):         my $stu_fullname = $env{'form.fullname'};
                   2142:):         if ($stu_fullname eq '') {
                   2143:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2144:):         }
                   2145:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2146:):         if ($forwhom ne '') {
                   2147:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2148:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2149:):         }
                   2150:):     }
1.468     albertel 2151:     $rendered=
1.588     bisitz   2152:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2153:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2154:        .$rendered
                   2155:        .'</div>';
1.468     albertel 2156:     $companswer=
1.588     bisitz   2157:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2158:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2159:        .$companswer
                   2160:        .'</div>';
1.468     albertel 2161:     my $result;
1.144     albertel 2162:     if ($mode eq 'both') {
1.588     bisitz   2163:         $result=$rendered.$companswer;
1.144     albertel 2164:     } elsif ($mode eq 'text') {
1.588     bisitz   2165:         $result=$rendered;
1.144     albertel 2166:     } elsif ($mode eq 'answer') {
1.588     bisitz   2167:         $result=$companswer;
1.144     albertel 2168:     }
1.71      ng       2169:     return $result;
1.58      albertel 2170: }
1.397     albertel 2171: 
1.396     banghart 2172: sub files_exist {
                   2173:     my ($r, $symb) = @_;
                   2174:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2175:     foreach my $student (@students) {
                   2176:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2177:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2178: 					      $udom,$uname);
1.396     banghart 2179:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2180:         foreach my $submission (@$string) {
                   2181:             my ($partid,$respid) =
                   2182: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2183:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2184: 					   \%record);
                   2185:             return 1 if (@$files);
1.396     banghart 2186:         }
                   2187:     }
1.397     albertel 2188:     return 0;
1.396     banghart 2189: }
1.397     albertel 2190: 
1.394     banghart 2191: sub download_all_link {
                   2192:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2193:0):     unless (&files_exist($r, $symb)) {
                   2194:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2195:0):         return;
                   2196:0):     }
1.395     albertel 2197:     my $all_students = 
                   2198: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2199: 
                   2200:     my $parts =
                   2201: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2202: 
1.394     banghart 2203:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2204:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2205:                              'cgi.'.$identifier.'.symb' => $symb,
                   2206:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2207:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2208: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2209:0):     return;
                   2210:0): }
                   2211:0): 
                   2212:0): sub submit_download_link {
                   2213:0):     my ($request,$symb) = @_;
                   2214:0):     if (!$symb) { return ''; }
                   2215:0):     my $res_error;
                   2216:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2217:0):         &response_type($symb,\$res_error);
                   2218:0):     if ($res_error) {
                   2219:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2220:0):         return;
                   2221:0):     }
                   2222:0):     unless ($numessay) {
                   2223:0):         $request->print(&mt('No essayresponse items found'));
                   2224:0):         return;
                   2225:0):     }
                   2226:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2227:0):     if (@chosenparts) {
                   2228:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2229:0):                                           undef,undef,1));
                   2230:0):     }
                   2231:0):     if ($numessay) {
                   2232:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2233:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2234:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2235:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2236:0):         if (ref($fullname) eq 'HASH') {
                   2237:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2238:0):             if (@students) {
                   2239:0):                 @{$env{'form.stuinfo'}} = @students;
                   2240:0):                 if ($numdropbox) {
                   2241:0):                     &download_all_link($request,$symb);
                   2242:0):                 } else {
                   2243:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2244:0):                 }
                   2245:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2246:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2247:0):             } else {
                   2248:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2249:0):             }
                   2250:0):         } else {
                   2251:0):             $request->print(&mt('Could not retrieve student information'));
                   2252:0):         }
                   2253:0):     } else {
                   2254:0):         $request->print(&mt('No essayresponse items found'));
                   2255:0):     }
                   2256:0):     return;
1.394     banghart 2257: }
1.395     albertel 2258: 
1.432     banghart 2259: sub build_section_inputs {
                   2260:     my $section_inputs;
                   2261:     if ($env{'form.section'} eq '') {
                   2262:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2263:     } else {
                   2264:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2265:         foreach my $section (@sections) {
1.432     banghart 2266:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2267:         }
                   2268:     }
                   2269:     return $section_inputs;
                   2270: }
                   2271: 
1.44      ng       2272: # --------------------------- show submissions of a student, option to grade 
                   2273: sub submission {
1.596.2.12.2.  1(raebur 2274:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2275:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2276:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2277:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2278:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2279:0): 
1.324     albertel 2280:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2281:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          5(raebur 2282:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2283: 
                   2284:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2285:4):         $request->print(
                   2286:4):             '<span class="LC_warning">'.
                   2287:4):             &mt('Unable to view requested student.').
                   2288:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2289:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2290:4):             '</span>');
1.104     albertel 2291: 	return;
                   2292:     }
                   2293: 
1.596.2.12.2.  1(raebur 2294:0):     my $res_error;
                   2295:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2296:0):         &response_type($symb,\$res_error);
                   2297:0):     if ($res_error) {
                   2298:0):         $request->print(&navmap_errormsg());
                   2299:0):         return;
                   2300:0):     }
                   2301:0): 
1.257     albertel 2302:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2303:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2304:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1.596.2.12.2.  1(raebur 2305:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2306:0):         $env{'form.compmsg'} = 1;
                   2307:0):     }
1.257     albertel 2308:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2309:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2310: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2311: 	'/check.gif" height="16" border="0" />';
1.41      ng       2312: 
                   2313:     # header info
                   2314:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2315:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2316:0):         if (@chosenparts) {
                   2317:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2318:0):         } elsif ($divforres) {
                   2319:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2320:0):         } else {
                   2321:0):             $request->print('<br clear="all" />');
                   2322:0):         }
1.41      ng       2323: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2324:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2325:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2326: 
1.44      ng       2327: 	# option to display problem, only once else it cause problems 
                   2328:         # with the form later since the problem has a form.
1.257     albertel 2329: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2330: 	    my $mode;
1.257     albertel 2331: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2332: 		$mode='both';
1.257     albertel 2333: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2334: 		$mode='text';
1.257     albertel 2335: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2336: 		$mode='answer';
                   2337: 	    }
1.329     albertel 2338: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2339: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2340: 	}
1.441     www      2341: 
1.41      ng       2342: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2343:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2344: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2345: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2346: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2347:0): 	}
                   2348:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2349:0): 	# if this subroutine has been called once.
                   2350:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2351: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2352: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2353: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2354: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2355: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2356:0): 	}
                   2357:0): 	if ($env{'form.compmsg'}) {
                   2358:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2359:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2360: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2361: 	}
1.596.2.12.2.  1(raebur 2362:0): 
1.257     albertel 2363: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2364: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2365: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2366: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2367: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2368: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2369: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2370: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2371: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2372: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2373: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2374: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2375: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2376:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2377: 			&build_section_inputs().
1.326     albertel 2378: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2379: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2380: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2381:0): 	if ($env{'form.compmsg'}) {
                   2382:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2383:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2384:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2385:0): 	}
                   2386:0): 	if ($numessay) {
1.257     albertel 2387: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2388: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2389: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2390:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2391: 	}
1.596.2.12.2.  1(raebur 2392:0): 
1.41      ng       2393: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2394: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2395: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2396: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2397: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2398: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2399: 		'" />'."\n".
                   2400: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2401: 	    $cts++;
                   2402: 	}
                   2403: 	$request->print($prnmsg);
1.32      ng       2404: 
1.596.2.12.2.  1(raebur 2405:0): 	if ($numessay) {
1.596.2.4  raeburn  2406: 
                   2407:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2408:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2409:                           keyw => 'Keyword Options',
                   2410:                           list => 'List',
                   2411:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2412:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2413:                      );
1.88      www      2414: #
                   2415: # Print out the keyword options line
                   2416: #
1.596.2.12.2.  1(raebur 2417:0): 	    $request->print(
          8(raebur 2418:4):                 '<div class="LC_columnSection">'
                   2419:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2420:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2421:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2422:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2423:4):  class="page">'.$lt{'past'}.'</a>',
                   2424:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2425:4):                     {legend => $lt{'keyw'}})
                   2426:4):                .'</fieldset></div>'
                   2427:4):             );
                   2428:4): 
1.88      www      2429: #
                   2430: # Load the other essays for similarity check
                   2431: #
1.596.2.12.2.  5(raebur 2432:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2433:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2434:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2435:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2436:9):                 if ($cdom ne '' && $cnum ne '') {
                   2437:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2438:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2439:9):                         my $apath = $1.'_'.$id;
                   2440:9):                         $apath=~s/\W/\_/gs;
                   2441:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2442:9):                     }
                   2443:9):                 }
                   2444:9):             } else {
                   2445:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2446:9): 	        $apath=&escape($apath);
                   2447:9): 	        $apath=~s/\W/\_/gs;
                   2448:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2449:9):             }
1.41      ng       2450:         }
                   2451:     }
1.44      ng       2452: 
1.441     www      2453: # This is where output for one specific student would start
1.592     bisitz   2454:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2455:     $request->print(
                   2456:         "\n\n"
                   2457:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2458:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2459:        ."\n"
                   2460:     );
1.441     www      2461: 
1.592     bisitz   2462:     # Show additional functions if allowed
                   2463:     if ($perm{'vgr'}) {
                   2464:         $request->print(
                   2465:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2466:3):                 'View recent activity',
1.592     bisitz   2467:                 $uname,$udom,'check')
                   2468:            .' '
                   2469:         );
                   2470:     }
                   2471:     if ($perm{'opa'}) {
                   2472:         $request->print(
                   2473:             &Apache::loncommon::pprmlink(
                   2474:                 &mt('Set/Change parameters'),
                   2475:                 $uname,$udom,$symb,'check'));
                   2476:     }
                   2477: 
                   2478:     # Show Problem
1.257     albertel 2479:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2480: 	my $mode;
1.257     albertel 2481: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2482: 	    $mode='both';
1.257     albertel 2483: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2484: 	    $mode='text';
1.257     albertel 2485: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2486: 	    $mode='answer';
                   2487: 	}
1.329     albertel 2488: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2489: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2490:     }
1.144     albertel 2491: 
1.257     albertel 2492:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2493: 
1.44      ng       2494:     # Display student info
1.41      ng       2495:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2496: 
                   2497:     my $result='<div class="LC_Box">'
                   2498:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2499:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2500:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  1(raebur 2501:0):     if ($numresp > $numessay) {
1.588     bisitz   2502:         $result.='<p class="LC_info">'
                   2503:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2504:                 ."</p>\n";
1.469     albertel 2505:     }
                   2506: 
1.596.2.12.2.  1(raebur 2507:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2508:     my $fullname;
                   2509:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2510:0):     if ($numessay) {
1.464     albertel 2511: 	(my $sub_result,$fullname,$col_fullnames)=
                   2512: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2513: 				 $counter);
                   2514: 	$result.=$sub_result;
1.41      ng       2515:     }
1.44      ng       2516:     $request->print($result."\n");
1.588     bisitz   2517: 
1.44      ng       2518:     # print student answer/submission
1.596.2.12.2.  1(raebur 2519:0):     # Options are (1) Last submission only
                   2520:0):     #             (2) Last submission (with detailed information for that submission)
                   2521:0):     #             (3) All transactions (by date)
                   2522:0):     #             (4) The whole record (with detailed information for all transactions)
                   2523:0): 
                   2524:0):     my ($string,$timestamp)= &get_last_submission(\%record);
                   2525:0): 
                   2526:0):     my $lastsubonly;
                   2527:0): 
                   2528:0):     if ($$timestamp eq '') {
                   2529:0):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2530:0):     } else {
                   2531:0):         $lastsubonly =
                   2532:0):             '<div class="LC_grade_submissions_body">'
                   2533:0):            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2534:0): 
                   2535:0): 	my %seenparts;
                   2536:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2537:0): 	foreach my $part (@part_response_id) {
                   2538:0): 	    my ($partid,$respid) = @{ $part };
                   2539:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2540:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2541:0): 		if (exists($seenparts{$partid})) { next; }
                   2542:0): 		$seenparts{$partid}=1;
                   2543:0):                 $request->print(
                   2544:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2545:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2546:0):                                '<a href="javascript:viewSubmitter(\''.
                   2547:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2548:0):                                '\');" target="_self">'.
                   2549:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2550:0):                     '<br />');
                   2551:0): 		next;
                   2552:0): 	    }
                   2553:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2554:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2555:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2556:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2557:0):                     ' <span class="LC_internal_info">'.
                   2558:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2559:0):                     '</span>&nbsp; &nbsp;'.
                   2560:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2561:0): 		next;
                   2562:0): 	    }
                   2563:0): 	    foreach my $submission (@$string) {
                   2564:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2565:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2566:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2567:0): 		# Similarity check
                   2568:0):                 my $similar='';
                   2569:0):                 my ($type,$trial,$rndseed);
                   2570:0):                 if ($hide eq 'rand') {
                   2571:0):                     $type = 'randomizetry';
                   2572:0):                     $trial = $record{"resource.$partid.tries"};
                   2573:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2574:0):                 }
                   2575:0): 		if ($env{'form.checkPlag'}) {
                   2576:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2577:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2578:0): 		    if ($osim) {
                   2579:0): 		        $osim=int($osim*100.0);
                   2580:0):                         if ($hide eq 'anon') {
                   2581:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2582:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2583:0):                         } else {
                   2584:0): 			    $similar='<hr />';
                   2585:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2586:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2587:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2588:0):                                                 $osim,
                   2589:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2590:0):                                             '</span></h3>';
                   2591:0):                             } elsif ($ocrsid ne '') {
                   2592:0):                                 my %old_course_desc;
                   2593:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2594:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2595:9):                                 } else {
          1(raebur 2596:0):                                     my $args;
                   2597:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2598:0):                                         $args = {'one_time' => 1};
                   2599:0):                                     }
                   2600:0):                                     %old_course_desc =
                   2601:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2602:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2603:9):                                 }
          1(raebur 2604:0):                                 $similar .=
                   2605:0):                                     '<h3><span class="LC_warning">'.
                   2606:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2607:0): 				        $osim,
                   2608:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2609:0): 				        $old_course_desc{'description'},
                   2610:0): 				        $old_course_desc{'num'},
                   2611:0): 				        $old_course_desc{'domain'}).
                   2612:0): 				    '</span></h3>';
1.596     raeburn  2613:                             } else {
1.596.2.12.2.  1(raebur 2614:0):                                 $similar .=
                   2615:0):                                     '<h3><span class="LC_warning">'.
                   2616:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2617:0):                                         $osim,
                   2618:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2619:0):                                     '</span></h3>';
1.596     raeburn  2620:                             }
1.596.2.12.2.  1(raebur 2621:0):                             $similar .= '<blockquote><i>'.
                   2622:0):                                         &keywords_highlight($oessay).
                   2623:0):                                         '</i></blockquote><hr />';
                   2624:0): 		        }
                   2625:0):                     }
                   2626:0):                 }
                   2627:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2628:0):                                      undef,$type,$trial,$rndseed);
                   2629:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2630:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2631:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2632:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2633:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2634:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2635:0):                         ' <span class="LC_internal_info">'.
                   2636:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2637:0):                         '</span>&nbsp; &nbsp;';
                   2638:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2639:0): 		    if (@$files) {
1.596.2.2  raeburn  2640:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2641:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2642:                         } else {
1.596.2.12.2.  1(raebur 2643:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2644:0):                                          .'<br /><span class="LC_warning">';
                   2645:0):                             if(@$files == 1) {
                   2646:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2647:0):                             } else {
                   2648:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2649:4):                             }
          1(raebur 2650:0):                             $lastsubonly .= '</span>';
                   2651:0):                             foreach my $file (@$files) {
                   2652:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2653:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2654:4):                             }
1.596     raeburn  2655:                         }
1.596.2.12.2.  1(raebur 2656:0): 			$lastsubonly.='<br />';
1.41      ng       2657: 		    }
1.596.2.12.2.  1(raebur 2658:0):                     if ($hide eq 'anon') {
                   2659:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2660:0):                     } else {
                   2661:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2662:0):                         if ($draft) {
                   2663:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2664:0):                         }
                   2665:0):                         $subval =
                   2666:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2667:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2668:0):                         if ($responsetype eq 'essay') {
                   2669:0):                             $subval =~ s{\n}{<br />}g;
                   2670:0):                         }
                   2671:0):                         $lastsubonly.=$subval."\n";
                   2672:0):                     }
                   2673:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2674:0): 		    $lastsubonly.='</div>';
1.41      ng       2675: 		}
                   2676: 	    }
1.151     albertel 2677: 	}
1.596.2.12.2.  1(raebur 2678:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2679:0):     }
                   2680:0):     $request->print($lastsubonly);
                   2681:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2682:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2683: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2684:3):     }
                   2685:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2686:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2687: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2688: 								 $env{'request.course.id'},
1.44      ng       2689: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2690:5): 								 'Apache::grades::keywords_highlight',
                   2691:5):                                                                  $usec,$identifier));
1.41      ng       2692:     }
1.121     ng       2693:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2694: 	.$udom.'" />'."\n");
1.44      ng       2695:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2696:0):     if (!&canmodify($usec)) {
                   2697:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2698:0):         return;
1.180     albertel 2699:     } else {
1.468     albertel 2700: 	$request->print('</div>'."\n");
1.41      ng       2701:     }
1.33      ng       2702: 
1.596.2.12.2.  1(raebur 2703:0):     # grading message center
                   2704:0): 
                   2705:0):     if ($env{'form.compmsg'}) {
                   2706:0):         my $result='<div class="LC_Box">'.
                   2707:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2708:0):                    '<div class="LC_grade_message_center_body">';
                   2709:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2710:0):         my $msgfor = $givenn.' '.$lastname;
                   2711:0):         if (scalar(@$col_fullnames) > 0) {
                   2712:0):             my $lastone = pop(@$col_fullnames);
                   2713:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2714:0):         }
                   2715:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2716:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2717:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2718:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2719:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2720:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2721:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2722:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2723:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2724:0):                  '<br />&nbsp;('.
                   2725:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2726:0): 	         '</div></div>';
                   2727:0):         $request->print($result);
1.118     ng       2728:     }
1.41      ng       2729: 
                   2730:     my %seen = ();
                   2731:     my @partlist;
1.129     ng       2732:     my @gradePartRespid;
1.375     albertel 2733:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2734:     $request->print(
1.588     bisitz   2735:         '<div class="LC_Box">'
                   2736:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2737:     );
1.592     bisitz   2738:     $request->print(&gradeBox_start());
1.375     albertel 2739:     foreach my $part_response_id (@part_response_id) {
                   2740:     	my ($partid,$respid) = @{ $part_response_id };
                   2741: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2742: 	next if ($seen{$partid} > 0);
1.41      ng       2743: 	$seen{$partid}++;
1.524     raeburn  2744: 	push(@partlist,$partid);
                   2745: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2746: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2747:     }
1.585     bisitz   2748:     $request->print(&gradeBox_end()); # </div>
                   2749:     $request->print('</div>');
1.468     albertel 2750: 
                   2751:     $request->print('<div class="LC_grade_info_links">');
                   2752:     $request->print('</div>');
                   2753: 
1.45      ng       2754:     $result='<input type="hidden" name="partlist'.$counter.
                   2755: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2756:     $result.='<input type="hidden" name="gradePartRespid'.
                   2757: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2758:     my $ctr = 0;
                   2759:     while ($ctr < scalar(@partlist)) {
                   2760: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2761: 	    $partlist[$ctr].'" />'."\n";
                   2762: 	$ctr++;
                   2763:     }
1.468     albertel 2764:     $request->print($result.''."\n");
1.41      ng       2765: 
1.441     www      2766: # Done with printing info for one student
                   2767: 
1.468     albertel 2768:     $request->print('</div>');#LC_grade_show_user
1.441     www      2769: 
                   2770: 
1.41      ng       2771:     # print end of form
                   2772:     if ($counter == $total) {
1.592     bisitz   2773:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2774: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2775: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2776: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2777: 	my $ntstu ='<select name="NTSTU">'.
                   2778: 	    '<option>1</option><option>2</option>'.
                   2779: 	    '<option>3</option><option>5</option>'.
                   2780: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2781: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2782: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2783:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2784: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2785: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2786: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2787: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2788:         $endform.='<span class="LC_warning">'.
                   2789:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2790:                   '</span>'."\n" ;
1.349     albertel 2791:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2792:             "' name='increment' />";
1.485     albertel 2793: 	$endform.='</td></tr></table></form>';
1.41      ng       2794: 	$request->print($endform);
                   2795:     }
                   2796:     return '';
1.38      ng       2797: }
                   2798: 
1.464     albertel 2799: sub check_collaborators {
                   2800:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2801:     my ($result,@col_fullnames);
                   2802:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2803:     foreach my $part (keys(%$handgrade)) {
                   2804: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2805: 					'.maxcollaborators',
                   2806: 					$symb,$udom,$uname);
                   2807: 	next if ($ncol <= 0);
                   2808: 	$part =~ s/\_/\./g;
                   2809: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2810: 	my (@good_collaborators, @bad_collaborators);
                   2811: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2812: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2813: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2814: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2815: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2816: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2817: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2818: 	    # Doing this grep allows 'fuzzy' specification
                   2819: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2820: 			       keys(%$classlist));
                   2821: 	    if (! scalar(@matches)) {
                   2822: 		push(@bad_collaborators, $possible_collaborator);
                   2823: 	    } else {
                   2824: 		push(@good_collaborators, @matches);
                   2825: 	    }
                   2826: 	}
                   2827: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2828: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2829: 	    foreach my $name (@good_collaborators) {
                   2830: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2831: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2832: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2833: 	    }
1.596.2.4  raeburn  2834: 	    $result.='</ol><br />'."\n";
1.466     albertel 2835: 	    my ($part)=split(/\./,$part);
1.464     albertel 2836: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2837: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2838: 		"\n";
                   2839: 	}
                   2840: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2841: 	    $result.='<div class="LC_warning">';
1.464     albertel 2842: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2843: 	    $result .= '</div>';
                   2844: 	}         
                   2845: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2846: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2847: 	    $result .= &mt('This student has submitted too many '.
                   2848: 		'collaborators.  Maximum is [_1].',$ncol);
                   2849: 	    $result .= '</div>';
                   2850: 	}
                   2851:     }
                   2852:     return ($result,$fullname,\@col_fullnames);
                   2853: }
                   2854: 
1.44      ng       2855: #--- Retrieve the last submission for all the parts
1.38      ng       2856: sub get_last_submission {
1.119     ng       2857:     my ($returnhash)=@_;
1.596     raeburn  2858:     my (@string,$timestamp,%lasthidden);
1.119     ng       2859:     if ($$returnhash{'version'}) {
1.46      ng       2860: 	my %lasthash=();
                   2861: 	my ($version);
1.119     ng       2862: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2863: 	    foreach my $key (sort(split(/\:/,
                   2864: 					$$returnhash{$version.':keys'}))) {
                   2865: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2866: 		$timestamp = 
1.545     raeburn  2867: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2868: 	    }
                   2869: 	}
1.596.2.2  raeburn  2870:         my (%typeparts,%randombytry);
1.596     raeburn  2871:         my $showsurv = 
                   2872:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2873:         foreach my $key (sort(keys(%lasthash))) {
                   2874:             if ($key =~ /\.type$/) {
                   2875:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2876:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2877:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2878:                     my ($ign,@parts) = split(/\./,$key);
                   2879:                     pop(@parts);
1.596.2.3  raeburn  2880:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2881:                     if ($lasthash{$key} eq 'randomizetry') {
                   2882:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2883:                     } else {
                   2884:                         unless ($showsurv) {
                   2885:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2886:                         }
1.596     raeburn  2887:                     }
                   2888:                     delete($lasthash{$key});
                   2889:                 }
                   2890:             }
                   2891:         }
                   2892:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2893:         my @randomize = keys(%randombytry);
1.397     albertel 2894: 	foreach my $key (keys(%lasthash)) {
                   2895: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2896:             my $hide;
                   2897:             if (@hidden) {
                   2898:                 foreach my $id (@hidden) {
                   2899:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2900:                         $hide = 'anon';
1.596     raeburn  2901:                         last;
                   2902:                     }
                   2903:                 }
                   2904:             }
1.596.2.2  raeburn  2905:             unless ($hide) {
                   2906:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2907:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2908:                         if ($key =~ /^\Q$id\E/) {
                   2909:                             $hide = 'rand';
                   2910:                             last;
                   2911:                         }
                   2912:                     }
                   2913:                 }
                   2914:             }
1.397     albertel 2915: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2916:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2917:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2918:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2919:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2920: 	}
                   2921:     }
1.397     albertel 2922:     if (!@string) {
                   2923: 	$string[0] =
1.539     riegler  2924: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2925:     }
                   2926:     return (\@string,\$timestamp);
1.38      ng       2927: }
1.35      ng       2928: 
1.44      ng       2929: #--- High light keywords, with style choosen by user.
1.38      ng       2930: sub keywords_highlight {
1.44      ng       2931:     my $string    = shift;
1.257     albertel 2932:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2933:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2934:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2935:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2936:     foreach my $keyword (@keylist) {
                   2937: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2938:     }
                   2939:     return $string;
1.38      ng       2940: }
1.36      ng       2941: 
1.596.2.12.2.  (raeburn 2942:): # For Tasks provide a mechanism to display previous version for one specific student
                   2943:): 
                   2944:): sub show_previous_task_version {
                   2945:):     my ($request,$symb) = @_;
                   2946:):     if ($symb eq '') {
          8(raebur 2947:4):         $request->print(
                   2948:4):             '<span class="LC_error">'.
                   2949:4):             &mt('Unable to handle ambiguous references.').
                   2950:4):             '</span>');
          (raeburn 2951:):         return '';
                   2952:):     }
                   2953:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2954:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2955:):     if (!&canview($usec)) {
          8(raebur 2956:4):         $request->print('<span class="LC_warning">'.
                   2957:4):                         &mt('Unable to view previous version for requested student.').
                   2958:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2959:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2960:4):                         '</span>');
          (raeburn 2961:):         return;
                   2962:):     }
                   2963:):     my $mode = 'both';
                   2964:):     my $isTask = ($symb =~/\.task$/);
                   2965:):     if ($isTask) {
                   2966:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2967:):             if ($env{'form.fullname'} eq '') {
                   2968:):                 $env{'form.fullname'} =
                   2969:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2970:):             }
                   2971:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2972:):             $request->print("\n\n".
                   2973:):                             '<div class="LC_grade_show_user">'.
                   2974:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2975:):                             '</h2>'."\n");
                   2976:):             &Apache::lonxml::clear_problem_counter();
                   2977:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2978:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2979:):             $request->print("\n</div>");
                   2980:):         }
                   2981:):     }
                   2982:):     return;
                   2983:): }
                   2984:): 
                   2985:): sub choose_task_version_form {
                   2986:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2987:):     my $isTask = ($symb =~/\.task$/);
                   2988:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2989:):     if ($isTask) {
                   2990:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2991:):                                               $udom,$uname);
                   2992:):         if (($record{'resource.0.version'} eq '') ||
                   2993:):             ($record{'resource.0.version'} < 2)) {
                   2994:):             return ($record{'resource.0.version'},
                   2995:):                     $record{'resource.0.version'},$result,$js);
                   2996:):         } else {
                   2997:):             $current = $record{'resource.0.version'};
                   2998:):         }
                   2999:):         if ($env{'form.previousversion'}) {
                   3000:):             $displayed = $env{'form.previousversion'};
                   3001:):             $rowtitle = &mt('Choose another version:')
                   3002:):         } else {
                   3003:):             $displayed = $current;
                   3004:):             $rowtitle = &mt('Show earlier version:');
                   3005:):         }
                   3006:):         $result = '<div class="LC_left_float">';
                   3007:):         my $list;
                   3008:):         my $numversions = 0;
                   3009:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3010:):             if ($i == $current) {
                   3011:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3012:):                     next;
                   3013:):                 } else {
                   3014:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3015:):                     $numversions ++;
                   3016:):                 }
                   3017:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3018:):                 unless ($i == $env{'form.previousversion'}) {
                   3019:):                     $numversions ++;
                   3020:):                 }
                   3021:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3022:):             }
                   3023:):         }
                   3024:):         if ($numversions) {
                   3025:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3026:):             $result .=
                   3027:):                 '<form name="getprev" method="post" action=""'.
                   3028:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3029:):                 &Apache::loncommon::start_data_table().
                   3030:):                 &Apache::loncommon::start_data_table_row().
                   3031:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3032:):                 '<td><select name="version">'.
                   3033:):                 '<option>'.&mt('Select').'</option>'.
                   3034:):                 $list.
                   3035:):                 '</select></td>'.
                   3036:):                 &Apache::loncommon::end_data_table_row();
                   3037:):             unless ($nomenu) {
                   3038:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3039:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3040:):                 '<td><span class="LC_nobreak">'.
                   3041:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3042:):                 &mt('Yes').'</label>'.
                   3043:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3044:):                 '</span></td>'.
                   3045:):                 &Apache::loncommon::end_data_table_row();
                   3046:):             }
                   3047:):             $result .=
                   3048:):                 &Apache::loncommon::start_data_table_row().
                   3049:):                 '<th align="left">&nbsp;</th>'.
                   3050:):                 '<td>'.
                   3051:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3052:):                 '</td>'.
                   3053:):                 &Apache::loncommon::end_data_table_row().
                   3054:):                 &Apache::loncommon::end_data_table().
                   3055:):                 '</form>';
                   3056:):             $js = &previous_display_javascript($nomenu,$current);
                   3057:):         } elsif ($displayed && $nomenu) {
                   3058:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3059:):         } else {
                   3060:):             $result .= &mt('No previous versions to show for this student');
                   3061:):         }
                   3062:):         $result .= '</div>';
                   3063:):     }
                   3064:):     return ($current,$displayed,$result,$js);
                   3065:): }
                   3066:): 
                   3067:): sub previous_display_javascript {
                   3068:):     my ($nomenu,$current) = @_;
                   3069:):     my $js = <<"JSONE";
                   3070:): <script type="text/javascript">
                   3071:): // <![CDATA[
                   3072:): function previousVersion(uname,udom,symb) {
                   3073:):     var current = '$current';
                   3074:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3075:):     var prevstr = new RegExp("^\\\\d+\$");
                   3076:):     if (!prevstr.test(version)) {
                   3077:):         return false;
                   3078:):     }
                   3079:):     var url = '';
                   3080:):     if (version == current) {
                   3081:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3082:):     } else {
                   3083:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3084:):     }
                   3085:): JSONE
                   3086:):     if ($nomenu) {
                   3087:):         $js .= <<"JSTWO";
                   3088:):     document.location.href = url;
                   3089:): JSTWO
                   3090:):     } else {
                   3091:):         $js .= <<"JSTHREE";
                   3092:):     var newwin = 0;
                   3093:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3094:):         if (document.getprev.prevwin[i].checked == true) {
                   3095:):             newwin = document.getprev.prevwin[i].value;
                   3096:):         }
                   3097:):     }
                   3098:):     if (newwin == 1) {
                   3099:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3100:):         url = url+'&inhibitmenu=yes';
                   3101:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3102:):             previousWin = window.open(url,'',options,1);
                   3103:):         } else {
                   3104:):             previousWin.location.href = url;
                   3105:):         }
                   3106:):         previousWin.focus();
                   3107:):         return false;
                   3108:):     } else {
                   3109:):         document.location.href = url;
                   3110:):         return false;
                   3111:):     }
                   3112:): JSTHREE
                   3113:):     }
                   3114:):     $js .= <<"ENDJS";
                   3115:):     return false;
                   3116:): }
                   3117:): // ]]>
                   3118:): </script>
                   3119:): ENDJS
                   3120:): 
                   3121:): }
                   3122:): 
1.44      ng       3123: #--- Called from submission routine
1.38      ng       3124: sub processHandGrade {
1.596.2.12.2.  1(raebur 3125:0):     my ($request,$symb) = @_;
1.324     albertel 3126:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3127:     my $button = $env{'form.gradeOpt'};
                   3128:     my $ngrade = $env{'form.NCT'};
                   3129:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3130:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3131:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3132: 
1.44      ng       3133:     if ($button eq 'Save & Next') {
                   3134: 	my $ctr = 0;
                   3135: 	while ($ctr < $ngrade) {
1.257     albertel 3136: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3137:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3138:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3139: 	    if ($errorflag eq 'no_score') {
                   3140: 		$ctr++;
                   3141: 		next;
                   3142: 	    }
1.104     albertel 3143: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3144:4):                 $request->print(
                   3145:4):                     '<span class="LC_error">'
                   3146:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3147:4):                    .'</span>');
1.104     albertel 3148: 		$ctr++;
                   3149: 		next;
                   3150: 	    }
1.596.2.12.2.  1(raebur 3151:5):             if ($numhidden) {
                   3152:5):                 $request->print(
                   3153:5):                     '<span class="LC_info">'
                   3154:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3155:5):                    .'</span><br />');
                   3156:5):             }
1.257     albertel 3157: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3158: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3159: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3160:             my ($feedurl,$showsymb) =
                   3161: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3162: 	    my $messagetail;
1.62      albertel 3163: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3164: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3165: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3166: 		$subject.=' ['.$restitle.']';
1.44      ng       3167: 		my (@msgnum) = split(/,/,$includemsg);
                   3168: 		foreach (@msgnum) {
1.257     albertel 3169: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3170: 		}
1.80      ng       3171: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3172: 		if ($env{'form.withgrades'.$ctr}) {
                   3173: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3174: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3175:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3176: 		}
                   3177: 		$msgstatus = 
                   3178:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3179: 						     $message.$messagetail,
1.418     albertel 3180:                                                      undef,$feedurl,undef,
1.386     raeburn  3181:                                                      undef,undef,$showsymb,
                   3182:                                                      $restitle);
1.574     bisitz   3183: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3184: 				$msgstatus.'<br />');
1.44      ng       3185: 	    }
1.257     albertel 3186: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3187: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3188: 		foreach my $collabstr (@collabstrs) {
                   3189: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3190: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3191: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3192: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3193: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3194: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3195: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3196: 			    next;
1.418     albertel 3197: 			} elsif ($message ne '') {
                   3198: 			    my ($baseurl,$showsymb) = 
                   3199: 				&get_feedurl_and_symb($symb,$collaborator,
                   3200: 						      $udom);
                   3201: 			    if ($env{'form.withgrades'.$ctr}) {
                   3202: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3203:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3204: 			    }
1.418     albertel 3205: 			    $msgstatus = 
                   3206: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3207: 			}
1.44      ng       3208: 		    }
                   3209: 		}
                   3210: 	    }
                   3211: 	    $ctr++;
                   3212: 	}
                   3213:     }
                   3214: 
1.596.2.12.2.  1(raebur 3215:0):     my $res_error;
                   3216:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3217:0):     if ($res_error) {
                   3218:0):         $request->print(&navmap_errormsg());
                   3219:0):         return;
                   3220:0):     }
                   3221:0): 
                   3222:0):     my %keyhash = ();
                   3223:0):     if ($numessay) {
1.119     ng       3224: 	# Keywords sorted in alphabatical order
1.257     albertel 3225: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3226: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3227:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3228: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3229: 	$env{'form.keywords'} = join(' ',@keywords);
                   3230: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3231: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3232: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3233: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3234: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3235:0):     }
1.119     ng       3236: 
1.596.2.12.2.  1(raebur 3237:0):     if ($env{'form.compmsg'}) {
1.119     ng       3238: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3239: 	# New messages are saved in env for the next student.
1.119     ng       3240: 	# All messages are saved in nohist_handgrade.db
                   3241: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3242: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3243: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3244: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3245: 		$idx++;
                   3246: 	    }
                   3247: 	    $ctr++;
1.41      ng       3248: 	}
1.119     ng       3249: 	$ctr = 0;
                   3250: 	while ($ctr < $ngrade) {
1.257     albertel 3251: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3252: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3253: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3254: 		$idx++;
                   3255: 	    }
                   3256: 	    $ctr++;
1.41      ng       3257: 	}
1.257     albertel 3258: 	$env{'form.savemsgN'} = --$idx;
                   3259: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3260:0):     }
                   3261:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3262: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3263: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3264:     }
1.596.2.12.2.  1(raebur 3265:0): 
1.44      ng       3266:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3267:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3268:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3269: 	my ($ctr,$total) = (0,0);
                   3270: 	while ($ctr < $ngrade) {
1.257     albertel 3271: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3272: 	    $ctr++;
                   3273: 	}
1.257     albertel 3274: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3275: 	$ctr = 0;
                   3276: 	while ($ctr < $total) {
1.257     albertel 3277: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3278: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3279: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3280:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3281: 	    $ctr++;
                   3282: 	}
                   3283: 	return '';
                   3284:     }
1.36      ng       3285: 
1.44      ng       3286:     # Get the next/previous one or group of students
1.257     albertel 3287:     my $firststu = $env{'form.unamedom0'};
                   3288:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3289:     my $ctr = 2;
1.41      ng       3290:     while ($laststu eq '') {
1.257     albertel 3291: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3292: 	$ctr++;
                   3293: 	$laststu = $firststu if ($ctr > $ngrade);
                   3294:     }
1.44      ng       3295: 
1.41      ng       3296:     my (@parsedlist,@nextlist);
                   3297:     my ($nextflg) = 0;
1.524     raeburn  3298:     foreach my $item (sort 
1.294     albertel 3299: 	     {
                   3300: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3301: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3302: 		 }
                   3303: 		 return $a cmp $b;
                   3304: 	     } (keys(%$fullname))) {
1.41      ng       3305: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3306: 	    push(@parsedlist,$item);
1.41      ng       3307: 	}
1.524     raeburn  3308: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3309: 	if ($button eq 'Previous') {
1.524     raeburn  3310: 	    last if ($item eq $firststu);
                   3311: 	    push(@parsedlist,$item);
1.41      ng       3312: 	}
                   3313:     }
                   3314:     $ctr = 0;
                   3315:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3316:     foreach my $student (@parsedlist) {
1.257     albertel 3317: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3318: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3319: 	
                   3320: 	if ($submitonly eq 'queued') {
                   3321: 	    my %queue_status = 
                   3322: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3323: 							$udom,$uname);
                   3324: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3325: 	}
                   3326: 
1.156     albertel 3327: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3328: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3329: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3330: 	    my $submitted = 0;
1.248     albertel 3331: 	    my $ungraded = 0;
                   3332: 	    my $incorrect = 0;
1.524     raeburn  3333: 	    foreach my $item (keys(%status)) {
                   3334: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3335: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3336: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3337: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3338: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3339: 		    $submitted = 0;
                   3340: 		}
1.41      ng       3341: 	    }
1.156     albertel 3342: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3343: 				     $submitonly eq 'incorrect' ||
                   3344: 				     $submitonly eq 'graded'));
1.248     albertel 3345: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3346: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3347: 	}
1.524     raeburn  3348: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3349: 	last if ($ctr == $ntstu);
1.41      ng       3350: 	$ctr++;
                   3351:     }
1.36      ng       3352: 
1.41      ng       3353:     $ctr = 0;
                   3354:     my $total = scalar(@nextlist)-1;
1.39      ng       3355: 
1.524     raeburn  3356:     foreach (sort(@nextlist)) {
1.41      ng       3357: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3358: 	$env{'form.student'}  = $uname;
                   3359: 	$env{'form.userdom'}  = $udom;
                   3360: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3361:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3362: 	$ctr++;
                   3363:     }
                   3364:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3365:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3366: 	$request->print($the_end);
                   3367:     }
                   3368:     return '';
1.38      ng       3369: }
1.36      ng       3370: 
1.44      ng       3371: #---- Save the score and award for each student, if changed
1.38      ng       3372: sub saveHandGrade {
1.324     albertel 3373:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3374:     my @version_parts;
1.104     albertel 3375:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3376: 					   $env{'request.course.id'});
1.104     albertel 3377:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3378:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3379:     my @parts_graded;
1.77      ng       3380:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3381:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3382:     my %aggregate = ();
                   3383:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3384:5):     if ($env{'form.HIDE'.$newflg}) {
                   3385:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3386:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3387:5):         $totchg += $numchgs;
                   3388:5):     }
1.301     albertel 3389:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3390:     foreach my $new_part (@parts) {
1.337     banghart 3391: 	#collaborator ($submi may vary for different parts
1.259     banghart 3392: 	if ($submitter && $new_part ne $part) { next; }
                   3393: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3394: 	if ($dropMenu eq 'excused') {
1.259     banghart 3395: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3396: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3397: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3398: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3399: 		}
1.364     banghart 3400: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3401: 	    }
1.125     ng       3402: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3403: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3404: 	    foreach my $key (keys(%record)) {
1.259     banghart 3405: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3406: 	    }
1.259     banghart 3407: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3408: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3409:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3410: 
                   3411:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3412: 					       [$new_part]);
                   3413:             my $aggtries =$totaltries;
1.269     raeburn  3414:             if ($last_resets{$new_part}) {
1.270     albertel 3415:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3416: 					   $new_part);
1.269     raeburn  3417:             }
1.270     albertel 3418: 
                   3419:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3420:             if ($aggtries > 0) {
1.327     albertel 3421:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3422:                 $aggregateflag = 1;
                   3423:             }
1.125     ng       3424: 	} elsif ($dropMenu eq '') {
1.259     banghart 3425: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3426: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3427: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3428: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3429: 		next;
                   3430: 	    }
1.259     banghart 3431: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3432: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3433: 	    my $partial= $pts/$wgt;
1.259     banghart 3434: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3435: 		#do not update score for part if not changed.
1.346     banghart 3436:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3437: 		next;
1.251     banghart 3438: 	    } else {
1.524     raeburn  3439: 	        push(@parts_graded,$new_part);
1.153     albertel 3440: 	    }
1.259     banghart 3441: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3442: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3443: 	    }
1.259     banghart 3444: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3445: 	    if ($partial == 0) {
1.153     albertel 3446: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3447: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3448: 		}
1.41      ng       3449: 	    } else {
1.153     albertel 3450: 		if ($record{$reckey} ne 'correct_by_override') {
                   3451: 		    $newrecord{$reckey} = 'correct_by_override';
                   3452: 		}
                   3453: 	    }	    
                   3454: 	    if ($submitter && 
1.259     banghart 3455: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3456: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3457: 	    }
1.259     banghart 3458: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3459: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3460: 	}
1.259     banghart 3461: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3462: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3463: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3464: 	        $dropMenu eq 'reset status')
                   3465: 	   {
1.524     raeburn  3466: 	    push(@version_parts,$new_part);
1.259     banghart 3467: 	}
1.41      ng       3468:     }
1.301     albertel 3469:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3470:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3471: 
1.344     albertel 3472:     if (%newrecord) {
                   3473:         if (@version_parts) {
1.364     banghart 3474:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3475:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3476: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3477: 	    foreach my $new_part (@version_parts) {
                   3478: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3479: 				$new_part,\%newrecord);
                   3480: 	    }
1.259     banghart 3481:         }
1.44      ng       3482: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3483: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3484: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3485: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3486:     }
1.269     raeburn  3487:     if ($aggregateflag) {
                   3488:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3489: 			      $cdom,$cnum);
1.269     raeburn  3490:     }
1.596.2.12.2.  1(raebur 3491:5):     return ('',$pts,$wgt,$totchg);
                   3492:5): }
                   3493:5): 
                   3494:5): sub makehidden {
                   3495:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3496:5):     return unless (ref($record) eq 'HASH');
                   3497:5):     my %modified;
                   3498:5):     my $numchanged = 0;
                   3499:5):     if (exists($record->{$version.':keys'})) {
                   3500:5):         my $partsregexp = $parts;
                   3501:5):         $partsregexp =~ s/,/|/g;
                   3502:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3503:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3504:5):                  my $item = $1;
                   3505:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3506:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3507:5):                  }
                   3508:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3509:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3510:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3511:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3512:5):             }
                   3513:5):         }
                   3514:5):         if (keys(%modified)) {
                   3515:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3516:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3517:5):                 $numchanged ++;
                   3518:5):             }
                   3519:5):         }
                   3520:5):     }
                   3521:5):     return $numchanged;
1.36      ng       3522: }
1.322     albertel 3523: 
1.380     albertel 3524: sub check_and_remove_from_queue {
                   3525:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3526:     my @ungraded_parts;
                   3527:     foreach my $part (@{$parts}) {
                   3528: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3529: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3530: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3531: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3532: 		) {
                   3533: 	    push(@ungraded_parts, $part);
                   3534: 	}
                   3535:     }
                   3536:     if ( !@ungraded_parts ) {
                   3537: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3538: 					       $cnum,$domain,$stuname);
                   3539:     }
                   3540: }
                   3541: 
1.337     banghart 3542: sub handback_files {
                   3543:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3544:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3545:     my $res_error;
                   3546:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3547:     if ($res_error) {
                   3548:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3549:         return;
                   3550:     }
1.596.2.4  raeburn  3551:     my @handedback;
                   3552:     my $file_msg;
1.375     albertel 3553:     my @part_response_id = &flatten_responseType($responseType);
                   3554:     foreach my $part_response_id (@part_response_id) {
                   3555:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3556: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3557:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3558:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3559:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3560: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3561:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3562:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3563:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3564:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3565: 		        &file_name_version_ext($answer_file);
1.355     banghart 3566: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3567:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3568:):                     my ($dir_list,$listerror) =
                   3569:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3570:):                                                  $domain,$stuname,$getpropath);
                   3571:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3572:3):                     # fix filename
1.355     banghart 3573:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3574:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3575:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3576:             	                                $save_file_name);
1.337     banghart 3577:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3578:                         $request->print('<br /><span class="LC_error">'.
                   3579:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3580:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3581:                                         '</span>');
1.356     banghart 3582:                     } else {
1.360     banghart 3583:                         # mark the file as read only
1.596.2.4  raeburn  3584:                         push(@handedback,$save_file_name);
1.367     albertel 3585: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3586: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3587: 			}
                   3588:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3589: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3590: 
1.337     banghart 3591:                     }
1.596.2.12.2.  3(raebur 3592: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 3593:                 }
                   3594:             }
                   3595:         }
1.596.2.4  raeburn  3596:     }
                   3597:     if (@handedback > 0) {
                   3598:         $request->print('<br />');
                   3599:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3600:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3601:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3602:         my ($subject,$message);
                   3603:         if (scalar(@handedback) == 1) {
                   3604:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3605:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3606:         } else {
                   3607:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3608:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3609:         }
                   3610:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3611:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3612:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3613:         my ($feedurl,$showsymb) =
                   3614:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3615:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3616:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3617:         my $msgstatus =
                   3618:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3619:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3620:                  $restitle);
                   3621:         if ($msgstatus) {
                   3622:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3623:         }
                   3624:     }
1.338     banghart 3625:     return;
1.337     banghart 3626: }
                   3627: 
1.418     albertel 3628: sub get_feedurl_and_symb {
                   3629:     my ($symb,$uname,$udom) = @_;
                   3630:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3631:     $url = &Apache::lonnet::clutter($url);
                   3632:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3633: 					$symb,$udom,$uname);
                   3634:     if ($encrypturl =~ /^yes$/i) {
                   3635: 	&Apache::lonenc::encrypted(\$url,1);
                   3636: 	&Apache::lonenc::encrypted(\$symb,1);
                   3637:     }
                   3638:     return ($url,$symb);
                   3639: }
                   3640: 
1.313     banghart 3641: sub get_submitted_files {
                   3642:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3643:     my @files;
                   3644:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3645:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3646:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3647:     	    push(@files,$file_url.$file);
                   3648:         }
                   3649:     }
                   3650:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3651:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3652:     }
                   3653:     return (\@files);
                   3654: }
1.322     albertel 3655: 
1.269     raeburn  3656: # ----------- Provides number of tries since last reset.
                   3657: sub get_num_tries {
                   3658:     my ($record,$last_reset,$part) = @_;
                   3659:     my $timestamp = '';
                   3660:     my $num_tries = 0;
                   3661:     if ($$record{'version'}) {
                   3662:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3663:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3664:                 $timestamp = $$record{$version.':timestamp'};
                   3665:                 if ($timestamp > $last_reset) {
                   3666:                     $num_tries ++;
                   3667:                 } else {
                   3668:                     last;
                   3669:                 }
                   3670:             }
                   3671:         }
                   3672:     }
                   3673:     return $num_tries;
                   3674: }
                   3675: 
                   3676: # ----------- Determine decrements required in aggregate totals 
                   3677: sub decrement_aggs {
                   3678:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3679:     my %decrement = (
                   3680:                         attempts => 0,
                   3681:                         users => 0,
                   3682:                         correct => 0
                   3683:                     );
                   3684:     $decrement{'attempts'} = $aggtries;
                   3685:     if ($solvedstatus =~ /^correct/) {
                   3686:         $decrement{'correct'} = 1;
                   3687:     }
                   3688:     if ($aggtries == $totaltries) {
                   3689:         $decrement{'users'} = 1;
                   3690:     }
1.524     raeburn  3691:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3692:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3693:     }
                   3694:     return;
                   3695: }
                   3696: 
                   3697: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3698: sub get_last_resets {
1.270     albertel 3699:     my ($symb,$courseid,$partids) =@_;
                   3700:     my %last_resets;
1.269     raeburn  3701:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3702:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3703:     my @keys;
                   3704:     foreach my $part (@{$partids}) {
                   3705: 	push(@keys,"$symb\0$part\0resettime");
                   3706:     }
                   3707:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3708: 				     $cdom,$cname);
                   3709:     foreach my $part (@{$partids}) {
                   3710: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3711:     }
1.270     albertel 3712:     return %last_resets;
1.269     raeburn  3713: }
                   3714: 
1.251     banghart 3715: # ----------- Handles creating versions for portfolio files as answers
                   3716: sub version_portfiles {
1.343     banghart 3717:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3718:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3719:     my @returned_keys;
1.255     banghart 3720:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3721:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3722:     foreach my $key (keys(%$record)) {
1.259     banghart 3723:         my $new_portfiles;
1.263     banghart 3724:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3725:             my @versioned_portfiles;
1.367     albertel 3726:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3727:             foreach my $file (@portfiles) {
1.306     banghart 3728:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3729:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3730: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3731: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3732:):                 my $getpropath = 1;
                   3733:):                 my ($dir_list,$listerror) =
                   3734:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3735:):                                              $stu_name,$getpropath);
                   3736:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3737:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3738:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3739:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3740:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3741:                         [$directory.$new_answer],
1.306     banghart 3742:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3743:                 }
1.252     banghart 3744:             }
1.343     banghart 3745:             $$record{$key} = join(',',@versioned_portfiles);
                   3746:             push(@returned_keys,$key);
1.251     banghart 3747:         }
                   3748:     } 
1.343     banghart 3749:     return (@returned_keys);   
1.305     banghart 3750: }
                   3751: 
1.307     banghart 3752: sub get_next_version {
1.341     banghart 3753:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3754:     my $version;
1.596.2.12.2.  (raeburn 3755:):     if (ref($dir_list) eq 'ARRAY') {
                   3756:):         foreach my $row (@{$dir_list}) {
                   3757:):             my ($file) = split(/\&/,$row,2);
                   3758:):             my ($file_name,$file_version,$file_ext) =
                   3759:): 	        &file_name_version_ext($file);
                   3760:):             if (($file_name eq $answer_name) && 
                   3761:): 	        ($file_ext eq $answer_ext)) {
                   3762:):                 # gets here if filename and extension match, 
                   3763:):                 # regardless of version
1.307     banghart 3764:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3765:):                     # a versioned file is found  so save it for later
                   3766:):                     if ($file_version > $version) {
                   3767:): 		        $version = $file_version;
                   3768:):                     }
1.307     banghart 3769: 	        }
                   3770:             }
                   3771:         }
1.596.2.12.2.  (raeburn 3772:):     }
1.307     banghart 3773:     $version ++;
                   3774:     return($version);
                   3775: }
                   3776: 
1.305     banghart 3777: sub version_selected_portfile {
1.306     banghart 3778:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3779:     my ($answer_name,$answer_ver,$answer_ext) =
                   3780:         &file_name_version_ext($file_name);
                   3781:     my $new_answer;
                   3782:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3783:     if($env{'form.copy'} eq '-1') {
                   3784:         $new_answer = 'problem getting file';
                   3785:     } else {
                   3786:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3787:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3788:                             $stu_name,$domain,'copy',
                   3789: 		        '/portfolio'.$directory.$new_answer);
                   3790:     }    
                   3791:     return ($new_answer);
1.251     banghart 3792: }
                   3793: 
1.304     albertel 3794: sub file_name_version_ext {
                   3795:     my ($file)=@_;
                   3796:     my @file_parts = split(/\./, $file);
                   3797:     my ($name,$version,$ext);
                   3798:     if (@file_parts > 1) {
                   3799: 	$ext=pop(@file_parts);
                   3800: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3801: 	    $version=pop(@file_parts);
                   3802: 	}
                   3803: 	$name=join('.',@file_parts);
                   3804:     } else {
                   3805: 	$name=join('.',@file_parts);
                   3806:     }
                   3807:     return($name,$version,$ext);
                   3808: }
                   3809: 
1.44      ng       3810: #--------------------------------------------------------------------------------------
                   3811: #
                   3812: #-------------------------- Next few routines handles grading by section or whole class
                   3813: #
                   3814: #--- Javascript to handle grading by section or whole class
1.42      ng       3815: sub viewgrades_js {
                   3816:     my ($request) = shift;
                   3817: 
1.539     riegler  3818:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3819:6):     &js_escape(\$alertmsg);
          1(raebur 3820:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3821:    function writePoint(partid,weight,point) {
1.125     ng       3822: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3823: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3824: 	if (point == "textval") {
1.125     ng       3825: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3826: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3827: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3828: 		var resetbox = false;
                   3829: 		for (var i=0; i<radioButton.length; i++) {
                   3830: 		    if (radioButton[i].checked) {
                   3831: 			textbox.value = i;
                   3832: 			resetbox = true;
                   3833: 		    }
                   3834: 		}
                   3835: 		if (!resetbox) {
                   3836: 		    textbox.value = "";
                   3837: 		}
                   3838: 		return;
                   3839: 	    }
1.109     matthew  3840: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3841: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3842: 				   ") greater than the weight for the part. Accept?");
                   3843: 		if (resp == false) {
                   3844: 		    textbox.value = "";
                   3845: 		    return;
                   3846: 		}
                   3847: 	    }
1.42      ng       3848: 	    for (var i=0; i<radioButton.length; i++) {
                   3849: 		radioButton[i].checked=false;
1.109     matthew  3850: 		if (parseFloat(point) == i) {
1.42      ng       3851: 		    radioButton[i].checked=true;
                   3852: 		}
                   3853: 	    }
1.41      ng       3854: 
1.42      ng       3855: 	} else {
1.125     ng       3856: 	    textbox.value = parseFloat(point);
1.42      ng       3857: 	}
1.41      ng       3858: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3859: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3860: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3861: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3862: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3863: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3864: 	    if (saveval != "correct") {
                   3865: 		scorename.value = point;
1.43      ng       3866: 		if (selname[0].selected != true) {
                   3867: 		    selname[0].selected = true;
                   3868: 		}
1.42      ng       3869: 	    }
                   3870: 	}
1.125     ng       3871: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3872:     }
                   3873: 
                   3874:     function writeRadText(partid,weight) {
1.125     ng       3875: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3876: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3877:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3878: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3879: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3880: 	    for (var i=0; i<radioButton.length; i++) {
                   3881: 		radioButton[i].checked=false;
                   3882: 
                   3883: 	    }
                   3884: 	    textbox.value = "";
                   3885: 
                   3886: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3887: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3888: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3889: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3890: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3891: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3892: 		if ((saveval != "correct") || override) {
1.42      ng       3893: 		    scorename.value = "";
1.125     ng       3894: 		    if (selval[1].selected) {
                   3895: 			selname[1].selected = true;
                   3896: 		    } else {
                   3897: 			selname[2].selected = true;
                   3898: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3899: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3900: 		    }
1.42      ng       3901: 		}
                   3902: 	    }
1.43      ng       3903: 	} else {
                   3904: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3905: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3906: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3907: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3908: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3909: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3910: 		if ((saveval != "correct") || override) {
1.125     ng       3911: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3912: 		    selname[0].selected = true;
                   3913: 		}
                   3914: 	    }
                   3915: 	}	    
1.42      ng       3916:     }
                   3917: 
                   3918:     function changeSelect(partid,user) {
1.125     ng       3919: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3920: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3921: 	var point  = textbox.value;
1.125     ng       3922: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3923: 
1.109     matthew  3924: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3925: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3926: 	    textbox.value = "";
                   3927: 	    return;
                   3928: 	}
1.109     matthew  3929: 	if (parseFloat(point) > parseFloat(weight)) {
                   3930: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3931: 			       ") greater than the weight of the part. Accept?");
                   3932: 	    if (resp == false) {
                   3933: 		textbox.value = "";
                   3934: 		return;
                   3935: 	    }
                   3936: 	}
1.42      ng       3937: 	selval[0].selected = true;
                   3938:     }
                   3939: 
                   3940:     function changeOneScore(partid,user) {
1.125     ng       3941: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3942: 	if (selval[1].selected || selval[2].selected) {
                   3943: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3944: 	    if (selval[2].selected) {
                   3945: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3946: 	    }
1.269     raeburn  3947:         }
1.42      ng       3948:     }
                   3949: 
                   3950:     function resetEntry(numpart) {
                   3951: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3952: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3953: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3954: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3955: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3956: 	    for (var i=0; i<radioButton.length; i++) {
                   3957: 		radioButton[i].checked=false;
                   3958: 
                   3959: 	    }
                   3960: 	    textbox.value = "";
                   3961: 	    selval[0].selected = true;
                   3962: 
                   3963: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3964: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3965: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3966: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3967: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3968: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3969: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3970: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3971: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3972: 		if (saveselval == "excused") {
1.43      ng       3973: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3974: 		} else {
1.43      ng       3975: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3976: 		}
                   3977: 	    }
1.41      ng       3978: 	}
1.42      ng       3979:     }
                   3980: 
1.41      ng       3981: VIEWJAVASCRIPT
1.42      ng       3982: }
                   3983: 
1.44      ng       3984: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3985: sub viewgrades {
1.596.2.12.2.  1(raebur 3986:0):     my ($request,$symb) = @_;
1.42      ng       3987:     &viewgrades_js($request);
1.41      ng       3988: 
1.168     albertel 3989:     #need to make sure we have the correct data for later EXT calls, 
                   3990:     #thus invalidate the cache
                   3991:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3992:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3993:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3994:     &Apache::lonnet::clear_EXT_cache_status();
                   3995: 
1.398     albertel 3996:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3997: 
                   3998:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3999:     $result.=&jscriptNform($symb);
1.41      ng       4000: 
1.44      ng       4001:     #beginning of class grading form
1.442     banghart 4002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4003:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4004: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4005: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4006: 	&build_section_inputs().
1.442     banghart 4007: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4008: 
1.596.2.12.2.  7(raebur 4009:6):     #retrieve selected groups
                   4010:6):     my (@groups,$group_display);
          8(raebur 4011:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4012:6):     if (grep(/^all$/,@groups)) {
                   4013:6):         @groups = ('all');
                   4014:6):     } elsif (grep(/^none$/,@groups)) {
                   4015:6):         @groups = ('none');
                   4016:6):     } elsif (@groups > 0) {
                   4017:6):         $group_display = join(', ',@groups);
                   4018:6):     }
                   4019:6): 
                   4020:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4021:1):     if ($env{'request.course.sec'} ne '') {
                   4022:1):         @sections = ($env{'request.course.sec'});
                   4023:1):     } else {
                   4024:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4025:1):     }
                   4026:1): 
                   4027:1): # Check if Save button should be usable
                   4028:1):     my $disabled = ' disabled="disabled"';
                   4029:1):     if ($perm{'mgr'}) {
                   4030:1):         if (grep(/^all$/,@sections)) {
                   4031:1):             undef($disabled);
                   4032:1):         } else {
                   4033:1):             foreach my $sec (@sections) {
                   4034:1):                 if (&canmodify($sec)) {
                   4035:1):                     undef($disabled);
                   4036:1):                     last;
                   4037:1):                 }
                   4038:1):             }
                   4039:1):         }
                   4040:1):     }
          7(raebur 4041:6):     if (grep(/^all$/,@sections)) {
                   4042:6):         @sections = ('all');
                   4043:6):         if ($group_display) {
                   4044:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4045:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4046:6):         } elsif (grep(/^none$/,@groups)) {
                   4047:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4048:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4049:6):         } else {
                   4050:6):             $common_header = &mt('Assign Common Grade to Class');
                   4051:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4052:6):         }
                   4053:6):     } elsif (grep(/^none$/,@sections)) {
                   4054:6):         @sections = ('none');
                   4055:6):         if ($group_display) {
                   4056:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4057:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4058:6):         } elsif (grep(/^none$/,@groups)) {
                   4059:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4060:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4061:6):         } else {
                   4062:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4063:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4064:6):         }
                   4065:6):     } else {
                   4066:6):         $section_display = join (", ",@sections);
                   4067:6):         if ($group_display) {
                   4068:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4069:6):                                  $section_display,$group_display);
                   4070:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4071:6):                                    $section_display,$group_display);
                   4072:6):         } elsif (grep(/^none$/,@groups)) {
                   4073:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4074:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4075:6):         } else {
                   4076:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4077:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4078:6):         }
1.52      albertel 4079:     }
1.596.2.12.2.  7(raebur 4080:6):     my %submit_types = &substatus_options();
                   4081:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4082:6): 
                   4083:6):     if ($env{'form.submitonly'} eq 'all') {
                   4084:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4085:6):     } else {
                   4086:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   4087:6):     }
                   4088:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4089:     #radio buttons/text box for assigning points for a section or class.
                   4090:     #handles different parts of a problem
1.582     raeburn  4091:     my $res_error;
                   4092:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4093:     if ($res_error) {
                   4094:         return &navmap_errormsg();
                   4095:     }
1.42      ng       4096:     my %weight = ();
                   4097:     my $ctsparts = 0;
1.45      ng       4098:     my %seen = ();
1.375     albertel 4099:     my @part_response_id = &flatten_responseType($responseType);
                   4100:     foreach my $part_response_id (@part_response_id) {
                   4101:     	my ($partid,$respid) = @{ $part_response_id };
                   4102: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4103: 	next if $seen{$partid};
                   4104: 	$seen{$partid}++;
1.42      ng       4105: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4106: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4107: 
1.324     albertel 4108: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4109: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4110: 	my $ctr = 0;
1.42      ng       4111: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4112: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4113: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4114: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4115: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4116: 	    $ctr++;
                   4117: 	}
1.485     albertel 4118: 	$radio.='</tr></table>';
                   4119: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4120: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4121: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4122: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4123:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4124:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4125:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4126: 		$weight{$partid}.')"> '.
1.401     albertel 4127: 	    '<option selected="selected"> </option>'.
1.485     albertel 4128: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4129: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4130: 	    '</select></td>'.
                   4131:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4132: 	$line.='<input type="hidden" name="partid_'.
                   4133: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4134: 	$line.='<input type="hidden" name="weight_'.
                   4135: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4136: 
                   4137: 	$result.=
                   4138: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4139: 	    '<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 4140: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4141: 	$ctsparts++;
1.41      ng       4142:     }
1.474     albertel 4143:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4144: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4145:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4146: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4147: 
1.44      ng       4148:     #table listing all the students in a section/class
                   4149:     #header of table
1.596.2.12.2.  7(raebur 4150:6):     if ($env{'form.submitonly'} eq 'all') { 
                   4151:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4152:6):     } else {
                   4153:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   4154:6):     }
                   4155:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4156: 	      &Apache::loncommon::start_data_table_header_row().
                   4157: 	      '<th>'.&mt('No.').'</th>'.
                   4158: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4159:     my $partserror;
                   4160:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4161:     if ($partserror) {
                   4162:         return &navmap_errormsg();
                   4163:     }
1.324     albertel 4164:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4165:     my @partids = ();
1.41      ng       4166:     foreach my $part (@parts) {
                   4167: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  4168:         my $narrowtext = &mt('Tries');
                   4169: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       4170: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 4171: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4172:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4173:0): #
                   4174:0): # FIXME: Looks like $display looks at English text
                   4175:0): #
1.324     albertel 4176: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4177: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4178: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4179:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4180:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4181: 	    next;
1.485     albertel 4182: 	    
1.207     albertel 4183: 	} else {
1.485     albertel 4184: 	    if ($display =~ /Problem Status/) {
                   4185: 		my $grade_status_mt = &mt('Grade Status');
                   4186: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4187: 	    }
                   4188: 	    my $part_mt = &mt('Part:');
                   4189: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4190: 	}
1.485     albertel 4191: 
1.474     albertel 4192: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4193:     }
1.474     albertel 4194:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4195: 
1.270     albertel 4196:     my %last_resets = 
                   4197: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4198: 
1.41      ng       4199:     #get info for each student
1.44      ng       4200:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4201:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4202:     my $ctr = 0;
1.294     albertel 4203:     foreach (sort 
                   4204: 	     {
                   4205: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4206: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4207: 		 }
                   4208: 		 return $a cmp $b;
                   4209: 	     } (keys(%$fullname))) {
1.324     albertel 4210: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 4211:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       4212:     }
1.474     albertel 4213:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4214:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4215:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4216: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4217:6):     if ($ctr == 0) {
1.442     banghart 4218:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4219:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4220:6):                 '<span class="LC_warning">';
                   4221:6):         if ($env{'form.submitonly'} eq 'all') {
                   4222:6):             if (grep(/^all$/,@sections)) {
                   4223:6):                 if (grep(/^all$/,@groups)) {
                   4224:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4225:6):                                    $stu_status);
                   4226:6):                 } elsif (grep(/^none$/,@groups)) {
                   4227:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4228:6):                                    $stu_status);
                   4229:6):                 } else {
                   4230:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4231:6):                                    $group_display,$stu_status);
                   4232:6):                 }
                   4233:6):             } elsif (grep(/^none$/,@sections)) {
                   4234:6):                 if (grep(/^all$/,@groups)) {
                   4235:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4236:6):                                    $stu_status);
                   4237:6):                 } elsif (grep(/^none$/,@groups)) {
                   4238:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4239:6):                                    $stu_status);
                   4240:6):                 } else {
                   4241:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4242:6):                                    $group_display,$stu_status);
                   4243:6):                 }
                   4244:6):             } else {
                   4245:6):                 if (grep(/^all$/,@groups)) {
                   4246:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4247:6):                                    $section_display,$stu_status);
                   4248:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4249:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4250:6):                                    $section_display,$stu_status);
                   4251:6):                 } else {
                   4252:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4253:6):                                    $section_display,$group_display,$stu_status);
                   4254:6):                 }
                   4255:6):             }
                   4256:6):         } else {
                   4257:6):             if (grep(/^all$/,@sections)) {
                   4258:6):                 if (grep(/^all$/,@groups)) {
                   4259:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4260:6):                                    $stu_status,$submission_status);
                   4261:6):                 } elsif (grep(/^none$/,@groups)) {
                   4262:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4263:6):                                    $stu_status,$submission_status);
                   4264:6):                 } else {
                   4265:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4266:6):                                    $group_display,$stu_status,$submission_status);
                   4267:6):                 }
                   4268:6):             } elsif (grep(/^none$/,@sections)) {
                   4269:6):                 if (grep(/^all$/,@groups)) {
                   4270:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4271:6):                                    $stu_status,$submission_status);
                   4272:6):                 } elsif (grep(/^none$/,@groups)) {
                   4273: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.',
                   4274:6):                                    $stu_status,$submission_status);
                   4275:6):                 } else {
                   4276: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.',
                   4277:6):                                    $group_display,$stu_status,$submission_status);
                   4278:6):                 }
                   4279:6):             } else {
                   4280:6):                 if (grep(/^all$/,@groups)) {
                   4281:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4282:6):                                    $section_display,$stu_status,$submission_status);
                   4283:6):                 } elsif (grep(/^none$/,@groups)) {
                   4284: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.',
                   4285:6):                                    $section_display,$stu_status,$submission_status);
                   4286:6):                 } else {
                   4287: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.',
                   4288:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4289:6):                 }
                   4290:6):             }
                   4291:6): 	}
                   4292:6): 	$result .= '</span><br />';
1.96      albertel 4293:     }
1.41      ng       4294:     return $result;
                   4295: }
                   4296: 
1.596.2.12.2.  7(raebur 4297:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4298: sub viewstudentgrade {
1.324     albertel 4299:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4300:     my ($uname,$udom) = split(/:/,$student);
                   4301:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4302:6):     my $submitonly = $env{'form.submitonly'};
                   4303:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4304:6):         my %partstatus = ();
                   4305:6):         if (ref($parts) eq 'ARRAY') {
                   4306:6):             foreach my $apart (@{$parts}) {
                   4307:6):                 my ($part,$type) = &split_part_type($apart);
                   4308:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4309:6):                 $status = 'nothing' if ($status eq '');
                   4310:6):                 $partstatus{$part}      = $status;
                   4311:6):                 my $subkey = "resource.$part.submitted_by";
                   4312:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4313:6):             }
                   4314:6):             my $submitted = 0;
                   4315:6):             my $graded = 0;
                   4316:6):             my $incorrect = 0;
                   4317:6):             foreach my $key (keys(%partstatus)) {
                   4318:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4319:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4320:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4321:6): 
                   4322:6):                 my $partid = (split(/\./,$key))[1];
                   4323:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4324:6):                     $submitted = 0;
                   4325:6):                 }
                   4326:6):             }
                   4327:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4328:6):                                        $submitonly eq 'incorrect' ||
                   4329:6):                                        $submitonly eq 'graded'));
                   4330:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4331:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4332:6):         }
                   4333:6):     }
                   4334:6):     if ($submitonly eq 'queued') {
                   4335:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4336:6):         my %queue_status =
                   4337:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4338:6):                                                     $udom,$uname);
                   4339:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4340:6):     }
                   4341:6):     $$ctr++;
                   4342:6):     my %aggregates = ();
1.474     albertel 4343:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4344:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4345:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4346: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4347: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4348: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4349:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4350:     foreach my $apart (@$parts) {
                   4351: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4352: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4353:         $result.='<td align="center">';
1.269     raeburn  4354:         my ($aggtries,$totaltries);
                   4355:         unless (exists($aggregates{$part})) {
1.270     albertel 4356: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4357: 
                   4358: 	    $aggtries = $totaltries;
1.269     raeburn  4359:             if ($$last_resets{$part}) {  
1.270     albertel 4360:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4361: 					   $part);
                   4362:             }
1.269     raeburn  4363:             $result.='<input type="hidden" name="'.
                   4364:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4365:             $result.='<input type="hidden" name="'.
                   4366:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4367:             $aggregates{$part} = 1;
                   4368:         }
1.41      ng       4369: 	if ($type eq 'awarded') {
1.320     albertel 4370: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4371: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4372: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4373: 	    $result.='<input type="text" name="'.
1.89      albertel 4374: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4375:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4376: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4377: 	} elsif ($type eq 'solved') {
                   4378: 	    my ($status,$foo)=split(/_/,$score,2);
                   4379: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4380: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4381: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4382: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4383: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4384:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4385: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4386: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4387: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4388: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4389: 	} else {
                   4390: 	    $result.='<input type="hidden" name="'.
                   4391: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4392: 		    "\n";
1.233     albertel 4393: 	    $result.='<input type="text" name="'.
1.122     ng       4394: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4395: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4396: 	}
                   4397:     }
1.474     albertel 4398:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4399:     return $result;
1.38      ng       4400: }
                   4401: 
1.44      ng       4402: #--- change scores for all the students in a section/class
                   4403: #    record does not get update if unchanged
1.38      ng       4404: sub editgrades {
1.596.2.12.2.  1(raebur 4405:0):     my ($request,$symb) = @_;
1.41      ng       4406: 
1.433     banghart 4407:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4408:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4409:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4410: 
1.477     albertel 4411:     my $result= &Apache::loncommon::start_data_table().
                   4412: 	&Apache::loncommon::start_data_table_header_row().
                   4413: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4414: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4415:     my %scoreptr = (
                   4416: 		    'correct'  =>'correct_by_override',
                   4417: 		    'incorrect'=>'incorrect_by_override',
                   4418: 		    'excused'  =>'excused',
                   4419: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4420:                     'credited' =>'credit_attempted',
1.43      ng       4421: 		    'nothing'  => '',
                   4422: 		    );
1.257     albertel 4423:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4424: 
1.44      ng       4425:     my (@partid);
                   4426:     my %weight = ();
1.54      albertel 4427:     my %columns = ();
1.44      ng       4428:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4429: 
1.582     raeburn  4430:     my $partserror;
                   4431:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4432:     if ($partserror) {
                   4433:         return &navmap_errormsg();
                   4434:     }
1.54      albertel 4435:     my $header;
1.257     albertel 4436:     while ($ctr < $env{'form.totalparts'}) {
                   4437: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4438: 	push(@partid,$partid);
1.257     albertel 4439: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4440: 	$ctr++;
1.54      albertel 4441:     }
1.324     albertel 4442:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4443:8):     my $totcolspan = 0;
1.54      albertel 4444:     foreach my $partid (@partid) {
1.478     albertel 4445: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4446: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4447: 	$columns{$partid}=2;
                   4448: 	foreach my $stores (@parts) {
                   4449: 	    my ($part,$type) = &split_part_type($stores);
                   4450: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4451: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4452: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4453: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4454:             my $narrowtext = &mt('Tries');
                   4455: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4456: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4457: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4458: 	    $columns{$partid}+=2;
                   4459: 	}
1.596.2.12.2.  2(raebur 4460:8):         $totcolspan += $columns{$partid};
1.54      albertel 4461:     }
                   4462:     foreach my $partid (@partid) {
1.324     albertel 4463: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4464: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4465: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4466: 	    '</th>';
1.54      albertel 4467: 
1.44      ng       4468:     }
1.477     albertel 4469:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4470: 	&Apache::loncommon::start_data_table_header_row().
                   4471: 	$header.
                   4472: 	&Apache::loncommon::end_data_table_header_row();
                   4473:     my @noupdate;
1.126     ng       4474:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4475:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4476: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4477: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4478: 	my %newrecord;
                   4479: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4480:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4481:8):         my $canmodify = &canmodify($usec);
                   4482:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4483:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4484:8):         if (!$canmodify) {
                   4485:8):             push(@noupdate,
                   4486:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4487:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4488:8):             next;
                   4489:8):         }
1.269     raeburn  4490:         my %aggregate = ();
                   4491:         my $aggregateflag = 0;
1.281     albertel 4492: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4493: 	foreach (@partid) {
1.257     albertel 4494: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4495: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4496: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4497: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4498: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4499: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4500: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4501: 	    my $score;
                   4502: 	    if ($partial eq '') {
1.257     albertel 4503: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4504: 	    } elsif ($partial > 0) {
                   4505: 		$score = 'correct_by_override';
                   4506: 	    } elsif ($partial == 0) {
                   4507: 		$score = 'incorrect_by_override';
                   4508: 	    }
1.257     albertel 4509: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4510: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4511: 
1.292     albertel 4512: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4513: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4514: 	    if ($dropMenu eq 'reset status' &&
                   4515: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4516: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4517: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4518: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4519: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4520: 		$updateflag = 1;
1.269     raeburn  4521:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4522:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4523:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4524:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4525:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4526:                     $aggregateflag = 1;
                   4527:                 }
1.139     albertel 4528: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4529: 		$updateflag = 1;
                   4530: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4531: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4532: 		$rec_update++;
1.125     ng       4533: 	    }
                   4534: 
1.93      albertel 4535: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4536: 		'<td align="center">'.$awarded.
                   4537: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4538: 
1.54      albertel 4539: 
                   4540: 	    my $partid=$_;
                   4541: 	    foreach my $stores (@parts) {
                   4542: 		my ($part,$type) = &split_part_type($stores);
                   4543: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4544: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4545: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4546: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4547: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4548: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4549: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4550: 		    $updateflag=1;
                   4551: 		}
1.93      albertel 4552: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4553: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4554: 	    }
1.44      ng       4555: 	}
1.477     albertel 4556: 	$line.="\n";
1.301     albertel 4557: 
                   4558: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4559: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4560: 
1.44      ng       4561: 	if ($updateflag) {
                   4562: 	    $count++;
1.257     albertel 4563: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4564: 				    $udom,$uname);
1.301     albertel 4565: 
                   4566: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4567: 					      $cnum,$udom,$uname)) {
                   4568: 		# need to figure out if should be in queue.
                   4569: 		my %record =  
                   4570: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4571: 					     $udom,$uname);
                   4572: 		my $all_graded = 1;
                   4573: 		my $none_graded = 1;
                   4574: 		foreach my $part (@parts) {
                   4575: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4576: 			$all_graded = 0;
                   4577: 		    } else {
                   4578: 			$none_graded = 0;
                   4579: 		    }
                   4580: 		}
                   4581: 
                   4582: 		if ($all_graded || $none_graded) {
                   4583: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4584: 							   $symb,$cdom,$cnum,
                   4585: 							   $udom,$uname);
                   4586: 		}
                   4587: 	    }
                   4588: 
1.477     albertel 4589: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4590: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4591: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4592: 	    $updateCtr++;
1.93      albertel 4593: 	} else {
1.477     albertel 4594: 	    push(@noupdate,
                   4595: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4596: 	    $noupdateCtr++;
1.44      ng       4597: 	}
1.269     raeburn  4598:         if ($aggregateflag) {
                   4599:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4600: 				  $cdom,$cnum);
1.269     raeburn  4601:         }
1.93      albertel 4602:     }
1.477     albertel 4603:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4604:8):         my $numcols=$totcolspan+2;
1.477     albertel 4605: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4606: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4607: 	    &mt('No Changes Occurred For the Students Below').
                   4608: 	    '</td>'.
1.477     albertel 4609: 	    &Apache::loncommon::end_data_table_row();
                   4610: 	foreach my $line (@noupdate) {
                   4611: 	    $result.=
                   4612: 		&Apache::loncommon::start_data_table_row().
                   4613: 		$line.
                   4614: 		&Apache::loncommon::end_data_table_row();
                   4615: 	}
1.44      ng       4616:     }
1.596.2.12.2.  1(raebur 4617:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4618:     my $msg = '<p><b>'.
                   4619: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4620: 	    $rec_update,$count).'</b><br />'.
                   4621: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4622: 	'</b></p>';
1.44      ng       4623:     return $title.$msg.$result;
1.5       albertel 4624: }
1.54      albertel 4625: 
                   4626: sub split_part_type {
                   4627:     my ($partstr) = @_;
                   4628:     my ($temp,@allparts)=split(/_/,$partstr);
                   4629:     my $type=pop(@allparts);
1.439     albertel 4630:     my $part=join('_',@allparts);
1.54      albertel 4631:     return ($part,$type);
                   4632: }
                   4633: 
1.44      ng       4634: #------------- end of section for handling grading by section/class ---------
                   4635: #
                   4636: #----------------------------------------------------------------------------
                   4637: 
1.5       albertel 4638: 
1.44      ng       4639: #----------------------------------------------------------------------------
                   4640: #
                   4641: #-------------------------- Next few routines handles grading by csv upload
                   4642: #
                   4643: #--- Javascript to handle csv upload
1.27      albertel 4644: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4645:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4646:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4647:6):   &js_escape(\$error1);
                   4648:6):   &js_escape(\$error2);
1.27      albertel 4649:   return(<<ENDPICK);
                   4650:   function verify(vf) {
                   4651:     var foundsomething=0;
                   4652:     var founduname=0;
1.243     albertel 4653:     var foundID=0;
1.27      albertel 4654:     for (i=0;i<=vf.nfields.value;i++) {
                   4655:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4656:       if (i==0 && tw!=0) { foundID=1; }
                   4657:       if (i==1 && tw!=0) { founduname=1; }
                   4658:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4659:     }
1.246     albertel 4660:     if (founduname==0 && foundID==0) {
                   4661: 	alert('$error1');
                   4662: 	return;
1.27      albertel 4663:     }
                   4664:     if (foundsomething==0) {
1.246     albertel 4665: 	alert('$error2');
                   4666: 	return;
1.27      albertel 4667:     }
                   4668:     vf.submit();
                   4669:   }
                   4670:   function flip(vf,tf) {
                   4671:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4672:     var i;
                   4673:     for (i=0;i<=vf.nfields.value;i++) {
                   4674:       //can not pick the same destination field for both name and domain
                   4675:       if (((i ==0)||(i ==1)) && 
                   4676:           ((tf==0)||(tf==1)) && 
                   4677:           (i!=tf) &&
                   4678:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4679:         eval('vf.f'+i+'.selectedIndex=0;')
                   4680:       }
                   4681:     }
                   4682:   }
                   4683: ENDPICK
                   4684: }
                   4685: 
                   4686: sub csvupload_javascript_forward_associate {
1.573     bisitz   4687:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4688:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4689:6):   &js_escape(\$error1);
                   4690:6):   &js_escape(\$error2);
1.27      albertel 4691:   return(<<ENDPICK);
                   4692:   function verify(vf) {
                   4693:     var foundsomething=0;
                   4694:     var founduname=0;
1.243     albertel 4695:     var foundID=0;
1.27      albertel 4696:     for (i=0;i<=vf.nfields.value;i++) {
                   4697:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4698:       if (tw==1) { foundID=1; }
                   4699:       if (tw==2) { founduname=1; }
                   4700:       if (tw>3) { foundsomething=1; }
1.27      albertel 4701:     }
1.246     albertel 4702:     if (founduname==0 && foundID==0) {
                   4703: 	alert('$error1');
                   4704: 	return;
1.27      albertel 4705:     }
                   4706:     if (foundsomething==0) {
1.246     albertel 4707: 	alert('$error2');
                   4708: 	return;
1.27      albertel 4709:     }
                   4710:     vf.submit();
                   4711:   }
                   4712:   function flip(vf,tf) {
                   4713:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4714:     var i;
                   4715:     //can not pick the same destination field twice
                   4716:     for (i=0;i<=vf.nfields.value;i++) {
                   4717:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4718:         eval('vf.f'+i+'.selectedIndex=0;')
                   4719:       }
                   4720:     }
                   4721:   }
                   4722: ENDPICK
                   4723: }
                   4724: 
1.26      albertel 4725: sub csvuploadmap_header {
1.324     albertel 4726:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4727:     my $javascript;
1.257     albertel 4728:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4729: 	$javascript=&csvupload_javascript_reverse_associate();
                   4730:     } else {
                   4731: 	$javascript=&csvupload_javascript_forward_associate();
                   4732:     }
1.45      ng       4733: 
1.257     albertel 4734:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4735:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4736:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4737:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4738:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4739:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4740:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4741:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4742:0): <br />
                   4743:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4744: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4745: <input type="hidden" name="associate"  value="" />
                   4746: <input type="hidden" name="phase"      value="three" />
                   4747: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4748: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4749: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4750: <input type="hidden" name="upfile_associate" 
1.257     albertel 4751:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4752: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4753: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4754: <hr />
                   4755: ENDPICK
1.596.2.12.2.  1(raebur 4756:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4757:     return '';
1.26      albertel 4758: 
                   4759: }
                   4760: 
                   4761: sub csvupload_fields {
1.582     raeburn  4762:     my ($symb,$errorref) = @_;
                   4763:     my (@parts) = &getpartlist($symb,$errorref);
                   4764:     if (ref($errorref)) {
                   4765:         if ($$errorref) {
                   4766:             return;
                   4767:         }
                   4768:     }
                   4769: 
1.556     weissno  4770:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4771: 		['username','Student Username'],
                   4772: 		['domain','Student Domain']);
1.324     albertel 4773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4774:     foreach my $part (sort(@parts)) {
                   4775: 	my @datum;
                   4776: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4777: 	my $name=$part;
                   4778: 	if  (!$display) { $display = $name; }
                   4779: 	@datum=($name,$display);
1.244     albertel 4780: 	if ($name=~/^stores_(.*)_awarded/) {
                   4781: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4782: 	}
1.41      ng       4783: 	push(@fields,\@datum);
                   4784:     }
                   4785:     return (@fields);
1.26      albertel 4786: }
                   4787: 
                   4788: sub csvuploadmap_footer {
1.41      ng       4789:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4790:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4791:     $request->print(<<ENDPICK);
1.26      albertel 4792: </table>
                   4793: <input type="hidden" name="nfields" value="$i" />
                   4794: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4795:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4796: </form>
                   4797: ENDPICK
                   4798: }
                   4799: 
1.283     albertel 4800: sub checkforfile_js {
1.539     riegler  4801:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4802:6):     &js_escape(\$alertmsg);
          1(raebur 4803:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4804:     function checkUpload(formname) {
                   4805: 	if (formname.upfile.value == "") {
1.539     riegler  4806: 	    alert("$alertmsg");
1.86      ng       4807: 	    return false;
                   4808: 	}
                   4809: 	formname.submit();
                   4810:     }
                   4811: CSVFORMJS
1.283     albertel 4812:     return $result;
                   4813: }
                   4814: 
                   4815: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4816:0):     my ($request,$symb) = @_;
1.283     albertel 4817:     if (!$symb) {return '';}
                   4818:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4819:0):     $result.=&Apache::loncommon::start_data_table().
                   4820:0):              &Apache::loncommon::start_data_table_header_row().
                   4821:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4822:0):              &Apache::loncommon::end_data_table_header_row().
                   4823:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4824:     my $upload=&mt("Upload Scores");
1.86      ng       4825:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4826:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4827:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4828:     $result.=<<ENDUPFORM;
1.106     albertel 4829: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4830: <input type="hidden" name="symb" value="$symb" />
                   4831: <input type="hidden" name="command" value="csvuploadmap" />
                   4832: $upfile_select
1.589     bisitz   4833: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4834: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4835: </form>
                   4836: ENDUPFORM
1.370     www      4837:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4838:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4839:0):             '</td>'.
                   4840:0):             &Apache::loncommon::end_data_table_row().
                   4841:0):             &Apache::loncommon::end_data_table();
1.86      ng       4842:     return $result;
                   4843: }
                   4844: 
                   4845: 
1.26      albertel 4846: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4847:0):     my ($request,$symb) = @_;
1.41      ng       4848:     if (!$symb) {return '';}
1.72      ng       4849: 
1.41      ng       4850:     my $datatoken;
1.257     albertel 4851:     if (!$env{'form.datatoken'}) {
1.41      ng       4852: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4853:     } else {
1.596.2.12.2.  3(raebur 4854:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4855:8):         if ($datatoken ne '') { 
                   4856:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4857:8):         }
1.26      albertel 4858:     }
1.41      ng       4859:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4860:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4861:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4862:     my ($i,$keyfields);
                   4863:     if (@records) {
1.582     raeburn  4864:         my $fieldserror;
                   4865: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4866:         if ($fieldserror) {
                   4867:             $request->print(&navmap_errormsg());
                   4868:             return;
                   4869:         }
1.257     albertel 4870: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4871: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4872: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4873: 							  \@fields);
                   4874: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4875: 	    chop($keyfields);
                   4876: 	} else {
                   4877: 	    unshift(@fields,['none','']);
                   4878: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4879: 							    \@fields);
1.311     banghart 4880:             foreach my $rec (@records) {
                   4881:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4882:                 if (%temp) {
                   4883:                     $keyfields=join(',',sort(keys(%temp)));
                   4884:                     last;
                   4885:                 }
                   4886:             }
1.41      ng       4887: 	}
                   4888:     }
                   4889:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4890: 
1.41      ng       4891:     return '';
1.27      albertel 4892: }
                   4893: 
1.246     albertel 4894: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 4895:0):     my ($request,$symb)= @_;
                   4896:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 4897:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4898:     my $ignore=&mt('Ignore First Line');
                   4899:     $request->print(<<ENDPICK);
                   4900: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4901: <input type="hidden" name="command"    value="csvuploadassign" />
                   4902: <p>
                   4903: <label>
                   4904:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 4905:0):    $overwrite
1.246     albertel 4906: </label>
                   4907: </p>
                   4908: ENDPICK
                   4909:     my %fields=&get_fields();
                   4910:     if (!defined($fields{'domain'})) {
1.257     albertel 4911: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 4912:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4913:     }
1.257     albertel 4914:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4915: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4916: 	my $cleankey=$1;
                   4917: 	if ($cleankey eq 'command') { next; }
                   4918: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4919: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4920:     }
                   4921:     # FIXME do a check for any duplicated user ids...
                   4922:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4923:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4924: <hr /></form>'."\n");
1.246     albertel 4925:     return '';
                   4926: }
                   4927: 
                   4928: sub get_fields {
                   4929:     my %fields;
1.257     albertel 4930:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4931:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4932: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4933: 	    if ($env{'form.f'.$i} ne 'none') {
                   4934: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4935: 	    }
                   4936: 	} else {
1.257     albertel 4937: 	    if ($env{'form.f'.$i} ne 'none') {
                   4938: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4939: 	    }
                   4940: 	}
1.27      albertel 4941:     }
1.246     albertel 4942:     return %fields;
                   4943: }
                   4944: 
                   4945: sub csvuploadassign {
1.596.2.12.2.  1(raebur 4946:0):     my ($request,$symb) = @_;
1.246     albertel 4947:     if (!$symb) {return '';}
1.345     bowersj2 4948:     my $error_msg = '';
1.596.2.12.2.  3(raebur 4949:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4950:8):     if ($datatoken ne '') {
                   4951:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4952:8):     }
1.246     albertel 4953:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4954:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4955:     my %fields=&get_fields();
1.257     albertel 4956:     my $courseid=$env{'request.course.id'};
1.97      albertel 4957:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4958:     my @notallowed;
1.41      ng       4959:     my @skipped;
1.596.2.4  raeburn  4960:     my @warnings;
1.41      ng       4961:     my $countdone=0;
                   4962:     foreach my $grade (@gradedata) {
                   4963: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4964: 	my $domain;
                   4965: 	if ($entries{$fields{'domain'}}) {
                   4966: 	    $domain=$entries{$fields{'domain'}};
                   4967: 	} else {
1.257     albertel 4968: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4969: 	}
1.243     albertel 4970: 	$domain=~s/\s//g;
1.41      ng       4971: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4972: 	$username=~s/\s//g;
1.243     albertel 4973: 	if (!$username) {
                   4974: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4975: 	    $id=~s/\s//g;
1.243     albertel 4976: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4977: 	    $username=$ids{$id};
                   4978: 	}
1.41      ng       4979: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4980: 	    my $id=$entries{$fields{'ID'}};
                   4981: 	    $id=~s/\s//g;
                   4982: 	    if ($id) {
                   4983: 		push(@skipped,"$id:$domain");
                   4984: 	    } else {
                   4985: 		push(@skipped,"$username:$domain");
                   4986: 	    }
1.41      ng       4987: 	    next;
                   4988: 	}
1.108     albertel 4989: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4990: 	if (!&canmodify($usec)) {
                   4991: 	    push(@notallowed,"$username:$domain");
                   4992: 	    next;
                   4993: 	}
1.244     albertel 4994: 	my %points;
1.41      ng       4995: 	my %grades;
                   4996: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4997: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4998: 		$dest eq 'domain') { next; }
                   4999: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5000: 	    if ($dest=~/stores_(.*)_points/) {
                   5001: 		my $part=$1;
                   5002: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5003: 					      $symb,$domain,$username);
1.345     bowersj2 5004:                 if ($wgt) {
                   5005:                     $entries{$fields{$dest}}=~s/\s//g;
                   5006:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5007:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5008:                                           : 'correct_by_override';
1.596.2.4  raeburn  5009:                     if ($pcr>1) {
                   5010:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5011:                     }
1.345     bowersj2 5012:                     $grades{"resource.$part.awarded"}=$pcr;
                   5013:                     $grades{"resource.$part.solved"}=$award;
                   5014:                     $points{$part}=1;
                   5015:                 } else {
                   5016:                     $error_msg = "<br />" .
                   5017:                         &mt("Some point values were assigned"
                   5018:                             ." for problems with a weight "
                   5019:                             ."of zero. These values were "
                   5020:                             ."ignored.");
                   5021:                 }
1.244     albertel 5022: 	    } else {
                   5023: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5024: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5025: 		my $store_key=$dest;
                   5026: 		$store_key=~s/^stores/resource/;
                   5027: 		$store_key=~s/_/\./g;
                   5028: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5029: 	    }
1.41      ng       5030: 	}
1.596.2.12.2.  1(raebur 5031:0): 	if (! %grades) {
1.508     www      5032:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5033:         } else {
                   5034: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5035: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5036: 					   $env{'request.course.id'},
                   5037: 					   $domain,$username);
1.508     www      5038: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5039:0): # Successfully stored
1.508     www      5040: 	      $request->print('.');
1.596.2.4  raeburn  5041: # Remove from grading queue
                   5042:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5043:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5044:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5045:                                              $domain,$username);
1.508     www      5046: 	   } else {
                   5047: 	      $request->print("<p><span class=\"LC_error\">".
                   5048:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5049:                                   "$username:$domain",$result)."</span></p>");
                   5050: 	   }
                   5051: 	   $request->rflush();
                   5052: 	   $countdone++;
                   5053:         }
1.41      ng       5054:     }
1.570     www      5055:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5056:     if (@warnings) {
                   5057:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5058:         $request->print(join(', ',@warnings));
                   5059:     }
1.41      ng       5060:     if (@skipped) {
1.571     www      5061: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5062:         $request->print(join(', ',@skipped));
1.106     albertel 5063:     }
                   5064:     if (@notallowed) {
1.571     www      5065: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5066: 	$request->print(join(', ',@notallowed));
1.41      ng       5067:     }
1.106     albertel 5068:     $request->print("<br />\n");
1.345     bowersj2 5069:     return $error_msg;
1.26      albertel 5070: }
1.44      ng       5071: #------------- end of section for handling csv file upload ---------
                   5072: #
                   5073: #-------------------------------------------------------------------
                   5074: #
1.122     ng       5075: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5076: #
                   5077: #--- Select a page/sequence and a student to grade
1.68      ng       5078: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5079:0):     my ($request,$symb) = @_;
1.68      ng       5080: 
1.539     riegler  5081:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5082:6):     &js_escape(\$alertmsg);
          1(raebur 5083:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5084: 
                   5085: function checkPickOne(formname) {
1.76      ng       5086:     if (radioSelection(formname.student) == null) {
1.539     riegler  5087: 	alert("$alertmsg");
1.68      ng       5088: 	return;
                   5089:     }
1.125     ng       5090:     ptr = pullDownSelection(formname.selectpage);
                   5091:     formname.page.value = formname["page"+ptr].value;
                   5092:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5093:     formname.submit();
                   5094: }
                   5095: 
                   5096: LISTJAVASCRIPT
1.118     ng       5097:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5098:0): 
1.257     albertel 5099:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5100:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5101:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5102:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5103: 
1.398     albertel 5104:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5105: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5106: 
1.80      ng       5107:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5108:     my $map_error;
                   5109:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5110:     if ($map_error) {
                   5111:         $request->print(&navmap_errormsg());
                   5112:         return; 
                   5113:     }
1.137     albertel 5114:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5115: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5116: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5117: 
1.596.2.12.2.  1(raebur 5118:0):     # Collection of hidden fields
                   5119:0):     my $ctr=0;
1.70      ng       5120:     foreach (@$titles) {
                   5121: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5122: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5123: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5124: 	$ctr++;
                   5125:     }
1.72      ng       5126:     $result.='<input type="hidden" name="page" />'."\n".
                   5127: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5128: 
1.432     banghart 5129:     $result.=&build_section_inputs();
1.442     banghart 5130:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5131:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5132:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5133:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5134:0): 
                   5135:0):     # Show grading options
                   5136:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5137:0):     my $select = '<select name="selectpage">'."\n";
                   5138:0):     $ctr=0;
                   5139:0):     foreach (@$titles) {
                   5140:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5141:0):         $select.='<option value="'.$ctr.'"'.
                   5142:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5143:0):             '>'.$showtitle.'</option>'."\n";
                   5144:0):         $ctr++;
                   5145:0):     }
                   5146:0):     $select.= '</select>';
1.72      ng       5147: 
1.596.2.12.2.  1(raebur 5148:0):     $result.=
                   5149:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5150:0):        .$select
                   5151:0):        .&Apache::lonhtmlcommon::row_closure();
                   5152:0): 
                   5153:0):     $result.=
                   5154:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5155:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5156:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5157:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5158:0):            .&mt('yes').'</label>'."\n"
                   5159:0):        .&Apache::lonhtmlcommon::row_closure();
                   5160:0): 
                   5161:0):     $result.=
                   5162:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5163:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5164:0):            .&mt('none').' </label>'."\n"
                   5165:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5166:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5167:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5168:0):            .&mt('all submissions with details').' </label>'
                   5169:0):        .&Apache::lonhtmlcommon::row_closure();
                   5170:0): 
                   5171:0):     $result.=
                   5172:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5173:0):        .'<input type="text" name="CODE" value="" />'
                   5174:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5175:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5176: 
1.596.2.12.2.  1(raebur 5177:0):     # Show list of students to select for grading
                   5178:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5179:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5180: 
1.68      ng       5181:     $request->print($result);
                   5182: 
1.485     albertel 5183:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5184: 	&Apache::loncommon::start_data_table().
                   5185: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5186: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5187: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5188: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5189: 	'<th>'.&nameUserString('header').'</th>'.
                   5190: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5191:  
1.596.2.12.2.  8(raebur 5192:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5193:     my $ptr = 1;
1.294     albertel 5194:     foreach my $student (sort 
                   5195: 			 {
                   5196: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5197: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5198: 			     }
                   5199: 			     return $a cmp $b;
                   5200: 			 } (keys(%$fullname))) {
1.68      ng       5201: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5202: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5203:                                   : '</td>');
1.126     ng       5204: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5205: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5206: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5207: 	$studentTable.=
                   5208: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5209:                          : '');
1.68      ng       5210: 	$ptr++;
                   5211:     }
1.484     albertel 5212:     if ($ptr%2 == 0) {
                   5213: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5214: 	    &Apache::loncommon::end_data_table_row();
                   5215:     }
                   5216:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5217:     $studentTable.='<input type="button" '.
1.589     bisitz   5218:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5219: 
                   5220:     $request->print($studentTable);
                   5221: 
                   5222:     return '';
                   5223: }
                   5224: 
                   5225: sub getSymbMap {
1.582     raeburn  5226:     my ($map_error) = @_;
1.132     bowersj2 5227:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5228:     unless (ref($navmap)) {
                   5229:         if (ref($map_error)) {
                   5230:             $$map_error = 'navmap';
                   5231:         }
                   5232:         return;
                   5233:     }
1.68      ng       5234:     my %symbx = ();
                   5235:     my @titles = ();
1.117     bowersj2 5236:     my $minder = 0;
                   5237: 
                   5238:     # Gather every sequence that has problems.
1.240     albertel 5239:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5240: 					       1,0,1);
1.117     bowersj2 5241:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 5242: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 5243: 	    my $title = $minder.'.'.
                   5244: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5245: 	    push(@titles, $title); # minder in case two titles are identical
                   5246: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5247: 	    $minder++;
1.241     albertel 5248: 	}
1.68      ng       5249:     }
                   5250:     return \@titles,\%symbx;
                   5251: }
                   5252: 
1.72      ng       5253: #
                   5254: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5255: sub displayPage {
1.596.2.12.2.  1(raebur 5256:0):     my ($request,$symb) = @_;
1.257     albertel 5257:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5258:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5259:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5260:     my $pageTitle = $env{'form.page'};
1.103     albertel 5261:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5262:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5263:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5264: 
                   5265:     #need to make sure we have the correct data for later EXT calls, 
                   5266:     #thus invalidate the cache
                   5267:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5268:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5269:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5270:     &Apache::lonnet::clear_EXT_cache_status();
                   5271: 
1.103     albertel 5272:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5273:0): 	$request->print(
                   5274:0):             '<span class="LC_warning">'.
                   5275:0):             &mt('Unable to view requested student. ([_1])',
                   5276:0):                 $env{'form.student'}).
                   5277:0):             '</span>');
          8(raebur 5278:4):         return;
1.103     albertel 5279:     }
1.398     albertel 5280:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5281:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5282: 	'</h3>'."\n";
1.500     albertel 5283:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5284:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5285: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5286:     } else {
                   5287: 	delete($env{'form.CODE'});
                   5288:     }
1.71      ng       5289:     &sub_page_js($request);
                   5290:     $request->print($result);
                   5291: 
1.132     bowersj2 5292:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5293:     unless (ref($navmap)) {
                   5294:         $request->print(&navmap_errormsg());
                   5295:         return;
                   5296:     }
1.257     albertel 5297:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5298:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5299:     if (!$map) {
1.485     albertel 5300: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5301: 	return; 
                   5302:     }
1.68      ng       5303:     my $iterator = $navmap->getIterator($map->map_start(),
                   5304: 					$map->map_finish());
                   5305: 
1.71      ng       5306:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5307: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5308: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5309: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5310: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5311: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5312: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5313:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5314: 
1.382     albertel 5315:     if (defined($env{'form.CODE'})) {
                   5316: 	$studentTable.=
                   5317: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5318:     }
1.381     albertel 5319:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5320: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5321: 
1.594     bisitz   5322:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5323:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5324:         '</span>'."\n".
1.484     albertel 5325: 	&Apache::loncommon::start_data_table().
                   5326: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5327:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5328: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5329: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5330: 
1.329     albertel 5331:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5332:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5333:     $iterator->next(); # skip the first BEGIN_MAP
                   5334:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5335:     while ($depth > 0) {
1.68      ng       5336:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5337:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5338: 
1.385     albertel 5339:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5340: 	    my $parts = $curRes->parts();
1.68      ng       5341:             my $title = $curRes->compTitle();
1.71      ng       5342: 	    my $symbx = $curRes->symb();
1.484     albertel 5343: 	    $studentTable.=
                   5344: 		&Apache::loncommon::start_data_table_row().
                   5345: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5346: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5347:2): 		                        : '<br />('.&mt('[_1]parts',
                   5348:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5349: 		 ).
                   5350: 		 '</td>';
1.71      ng       5351: 	    $studentTable.='<td valign="top">';
1.382     albertel 5352: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5353: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5354: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5355: 					     undef,'both',\%form);
1.71      ng       5356: 	    } else {
1.382     albertel 5357: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5358: 		$companswer =~ s|<form(.*?)>||g;
                   5359: 		$companswer =~ s|</form>||g;
1.71      ng       5360: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5361: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5362: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5363: #		}
1.116     ng       5364: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5365: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5366: 	    }
                   5367: 
1.257     albertel 5368: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5369: 
1.257     albertel 5370: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5371: 		if ($record{'version'} eq '') {
1.485     albertel 5372: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5373: 		} else {
1.116     ng       5374: 		    my %responseType = ();
                   5375: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5376: 			my @responseIds =$curRes->responseIds($partid);
                   5377: 			my @responseType =$curRes->responseType($partid);
                   5378: 			my %responseIds;
                   5379: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5380: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5381: 			}
                   5382: 			$responseType{$partid} = \%responseIds;
1.116     ng       5383: 		    }
1.148     albertel 5384: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5385: 
1.71      ng       5386: 		}
1.257     albertel 5387: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5388: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5389:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5390: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5391: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5392:5): 									'','.submission',undef,
                   5393:5):                                                                         $usec,$identifier);
1.71      ng       5394:  
                   5395: 	    }
1.103     albertel 5396: 	    if (&canmodify($usec)) {
1.585     bisitz   5397:             $studentTable.=&gradeBox_start();
1.103     albertel 5398: 		foreach my $partid (@{$parts}) {
                   5399: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5400: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5401: 		    $question++;
                   5402: 		}
1.585     bisitz   5403:             $studentTable.=&gradeBox_end();
1.196     albertel 5404: 		$prob++;
1.71      ng       5405: 	    }
                   5406: 	    $studentTable.='</td></tr>';
1.68      ng       5407: 
1.103     albertel 5408: 	}
1.68      ng       5409:         $curRes = $iterator->next();
                   5410:     }
1.596.2.12.2.  6(raebur 5411:1):     my $disabled;
                   5412:1):     unless (&canmodify($usec)) {
                   5413:1):         $disabled = ' disabled="disabled"';
                   5414:1):     }
1.68      ng       5415: 
1.589     bisitz   5416:     $studentTable.=
                   5417:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5418:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5419:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5420:         '</form>'."\n";
1.71      ng       5421:     $request->print($studentTable);
                   5422: 
                   5423:     return '';
1.119     ng       5424: }
                   5425: 
                   5426: sub displaySubByDates {
1.148     albertel 5427:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5428:     my $isCODE=0;
1.335     albertel 5429:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5430:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5431:     my $studentTable=&Apache::loncommon::start_data_table().
                   5432: 	&Apache::loncommon::start_data_table_header_row().
                   5433: 	'<th>'.&mt('Date/Time').'</th>'.
                   5434: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5435:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5436: 	'<th>'.&mt('Submission').'</th>'.
                   5437: 	'<th>'.&mt('Status').'</th>'.
                   5438: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5439:     my ($version);
                   5440:     my %mark;
1.148     albertel 5441:     my %orders;
1.119     ng       5442:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5443:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5444: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5445:     }
1.335     albertel 5446: 
                   5447:     my $interaction;
1.525     raeburn  5448:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5449:5):     my (%lastrndseed,%lasttype);
1.119     ng       5450:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5451: 	my $timestamp = 
                   5452: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5453: 	if (exists($$record{$version.':resource.0.version'})) {
                   5454: 	    $interaction = $$record{$version.':resource.0.version'};
                   5455: 	}
1.596.2.12.2.  (raeburn 5456:):         if ($isTask && $env{'form.previousversion'}) {
                   5457:):             next unless ($interaction == $env{'form.previousversion'});
                   5458:):         }
1.335     albertel 5459: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5460: 		             : "$version:resource");
1.467     albertel 5461: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5462: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5463: 	if ($isCODE) {
                   5464: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5465: 	}
1.596.2.12.2.  (raeburn 5466:):         if ($isTask) {
                   5467:):             $studentTable.='<td>'.$interaction.'</td>';
                   5468:):         }
1.119     ng       5469: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5470: 	my @displaySub = ();
                   5471: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5472:             my ($hidden,$type);
                   5473:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5474:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5475:                 $hidden = 1;
                   5476:             }
1.596.2.12.2.  1(raebur 5477:0): 	    my @matchKey;
                   5478:0):             if ($isTask) {
                   5479:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
                   5480:0):             } else {
                   5481:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5482:0):             }
1.122     ng       5483: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5484: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5485: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5486: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5487: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5488:                     
1.335     albertel 5489: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5490: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5491:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5492:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5493:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5494:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5495:                                    .'</span>'
                   5496:                                    .' <b>';
1.596     raeburn  5497:                     if ($hidden) {
                   5498:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5499:                     } else {
1.596.2.2  raeburn  5500:                         my ($trial,$rndseed,$newvariation);
                   5501:                         if ($type eq 'randomizetry') {
                   5502:                             $trial = $$record{"$where.$partid.tries"};
                   5503:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5504:                         }
1.596     raeburn  5505: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5506: 			    $displaySub[0].=&mt('Trial not counted');
                   5507: 		        } else {
                   5508: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5509: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5510:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5511:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5512:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5513:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5514:                                 }
                   5515:                             }
1.596.2.12.2.  4(raebur 5516:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5517:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5518: 		        }
                   5519: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5520:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5521: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5522: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5523: 			    $orders{$partid}->{$responseId}=
                   5524: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5525:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5526: 		        }
1.596.2.2  raeburn  5527: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5528: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5529: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5530:                     }
1.147     albertel 5531: 		}
                   5532: 	    }
1.335     albertel 5533: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5534: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5535: 				    $$record{"$where.$partid.checkedin"},
                   5536: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5537: 					'<br />';
1.335     albertel 5538: 	    }
                   5539: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5540: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5541: 		    lc($$record{"$where.$partid.award"}).' '.
                   5542: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5543: 		    '<br />';
                   5544: 	    }
1.335     albertel 5545: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5546: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5547: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5548: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5549: 		$displaySub[2].=
                   5550: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5551: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5552: 	    }
                   5553: 	}
                   5554: 	# needed because old essay regrader has not parts info
                   5555: 	if (exists $$record{"$version:resource.regrader"}) {
                   5556: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5557: 	}
                   5558: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5559: 	if ($displaySub[2]) {
1.467     albertel 5560: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5561: 	}
1.467     albertel 5562: 	$studentTable.='&nbsp;</td>'.
                   5563: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5564:     }
1.467     albertel 5565:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5566:     return $studentTable;
1.71      ng       5567: }
                   5568: 
                   5569: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5570:0):     my ($request,$symb) = @_;
1.71      ng       5571: 
1.257     albertel 5572:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5573:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5574:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5575:     my $pageTitle = $env{'form.page'};
1.103     albertel 5576:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5577:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5578:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5579:     if (!&canmodify($usec)) {
1.526     raeburn  5580: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5581: 	return;
                   5582:     }
1.398     albertel 5583:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5584:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5585: 	'</h3>'."\n";
1.70      ng       5586: 
1.68      ng       5587:     $request->print($result);
                   5588: 
1.582     raeburn  5589: 
1.132     bowersj2 5590:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5591:     unless (ref($navmap)) {
                   5592:         $request->print(&navmap_errormsg());
                   5593:         return;
                   5594:     }
1.257     albertel 5595:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5596:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5597:     if (!$map) {
1.527     raeburn  5598: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5599: 	return; 
                   5600:     }
1.71      ng       5601:     my $iterator = $navmap->getIterator($map->map_start(),
                   5602: 					$map->map_finish());
1.70      ng       5603: 
1.484     albertel 5604:     my $studentTable=
                   5605: 	&Apache::loncommon::start_data_table().
                   5606: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5607: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5608: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5609: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5610: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5611: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5612: 
                   5613:     $iterator->next(); # skip the first BEGIN_MAP
                   5614:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5615:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5616:     while ($depth > 0) {
1.71      ng       5617:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5618:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5619: 
1.385     albertel 5620:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5621: 	    my $parts = $curRes->parts();
1.71      ng       5622:             my $title = $curRes->compTitle();
                   5623: 	    my $symbx = $curRes->symb();
1.484     albertel 5624: 	    $studentTable.=
                   5625: 		&Apache::loncommon::start_data_table_row().
                   5626: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5627: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5628:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5629: 		.')').'</td>';
1.71      ng       5630: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5631: 
                   5632: 	    my %newrecord=();
                   5633: 	    my @displayPts=();
1.269     raeburn  5634:             my %aggregate = ();
                   5635:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5636:5):             if ($env{'form.HIDE'.$prob}) {
                   5637:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5638:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5639:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5640:5):                 $hideflag += $numchgs;
                   5641:5):             }
1.71      ng       5642: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5643: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5644: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5645: 
1.257     albertel 5646: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5647: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5648: 		my $partial = $newpts/$wgt;
                   5649: 		my $score;
                   5650: 		if ($partial > 0) {
                   5651: 		    $score = 'correct_by_override';
1.125     ng       5652: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5653: 		    $score = 'incorrect_by_override';
                   5654: 		}
1.257     albertel 5655: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5656: 		if ($dropMenu eq 'excused') {
1.71      ng       5657: 		    $partial = '';
                   5658: 		    $score = 'excused';
1.125     ng       5659: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5660: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5661: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5662: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5663: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5664: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5665: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5666: 		    $changeflag++;
                   5667: 		    $newpts = '';
1.269     raeburn  5668:                     
                   5669:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5670:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5671:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5672:                     if ($aggtries > 0) {
                   5673:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5674:                         $aggregateflag = 1;
                   5675:                     }
1.71      ng       5676: 		}
1.324     albertel 5677: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5678: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5679: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5680: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5681: 		    '&nbsp;<br />';
1.526     raeburn  5682: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5683: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5684: 		    '&nbsp;<br />';
1.71      ng       5685: 		$question++;
1.380     albertel 5686: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5687: 
1.71      ng       5688: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5689: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5690: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5691: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5692: 
                   5693: 		$changeflag++;
                   5694: 	    }
                   5695: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5696: 		my %record = 
                   5697: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5698: 					     $udom,$uname);
                   5699: 
                   5700: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5701: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5702: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5703: 		    $newrecord{'resource.CODE'} = '';
                   5704: 		}
1.257     albertel 5705: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5706: 					$udom,$uname);
1.382     albertel 5707: 		%record = &Apache::lonnet::restore($symbx,
                   5708: 						   $env{'request.course.id'},
                   5709: 						   $udom,$uname);
1.380     albertel 5710: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5711: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5712: 	    }
1.380     albertel 5713: 	    
1.269     raeburn  5714:             if ($aggregateflag) {
                   5715:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5716:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5717:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5718:             }
1.125     ng       5719: 
1.71      ng       5720: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5721: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5722: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5723: 
1.196     albertel 5724: 	    $prob++;
1.68      ng       5725: 	}
1.71      ng       5726:         $curRes = $iterator->next();
1.68      ng       5727:     }
1.98      albertel 5728: 
1.484     albertel 5729:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5730:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5731: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5732:5): 		  $changeflag).'<br />');
                   5733:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5734:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5735:5):                      $hideflag).'<br />');
                   5736:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5737: 
1.70      ng       5738:     return '';
                   5739: }
                   5740: 
1.72      ng       5741: #-------- end of section for handling grading by page/sequence ---------
                   5742: #
                   5743: #-------------------------------------------------------------------
                   5744: 
1.581     www      5745: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5746: #
                   5747: #------ start of section for handling grading by page/sequence ---------
                   5748: 
1.423     albertel 5749: =pod
                   5750: 
                   5751: =head1 Bubble sheet grading routines
                   5752: 
1.424     albertel 5753:   For this documentation:
                   5754: 
                   5755:    'scanline' refers to the full line of characters
                   5756:    from the file that we are parsing that represents one entire sheet
                   5757: 
                   5758:    'bubble line' refers to the data
1.596.2.6  raeburn  5759:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5760: 
                   5761: 
1.596.2.6  raeburn  5762: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5763: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5764: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5765: one of the predefined configurations for what each scanline looks
                   5766: like.
                   5767: 
                   5768: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5769: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5770: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5771:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5772: invalid student/employee ID
1.424     albertel 5773: 
                   5774: If the CODE option is used that determines the randomization of the
1.556     weissno  5775: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5776: username:domain.
                   5777: 
                   5778: During the validation phase the instructor can choose to skip scanlines. 
                   5779: 
1.596.2.6  raeburn  5780: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5781: 
                   5782:   scantron_original_filename (unmodified original file)
                   5783:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5784:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5785: 
                   5786: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5787: correction information that isn't representable in the bubblesheet
1.424     albertel 5788: file (see &scantron_getfile() for more information)
                   5789: 
                   5790: After all scanlines are either valid, marked as valid or skipped, then
                   5791: foreach line foreach problem in the picked sequence, an ssi request is
                   5792: made that simulates a user submitting their selected letter(s) against
                   5793: the homework problem.
1.423     albertel 5794: 
                   5795: =over 4
                   5796: 
                   5797: 
                   5798: 
                   5799: =item defaultFormData
                   5800: 
                   5801:   Returns html hidden inputs used to hold context/default values.
                   5802: 
                   5803:  Arguments:
                   5804:   $symb - $symb of the current resource 
                   5805: 
                   5806: =cut
1.422     foxr     5807: 
1.81      albertel 5808: sub defaultFormData {
1.324     albertel 5809:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 5810:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5811: }
                   5812: 
1.447     foxr     5813: 
1.423     albertel 5814: =pod 
                   5815: 
                   5816: =item getSequenceDropDown
                   5817: 
                   5818:    Return html dropdown of possible sequences to grade
                   5819:  
                   5820:  Arguments:
1.582     raeburn  5821:    $symb - $symb of the current resource
                   5822:    $map_error - ref to scalar which will container error if
                   5823:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5824: 
                   5825: =cut
1.422     foxr     5826: 
1.75      albertel 5827: sub getSequenceDropDown {
1.582     raeburn  5828:     my ($symb,$map_error)=@_;
1.75      albertel 5829:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5830:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5831:     if (ref($map_error)) {
                   5832:         return if ($$map_error);
                   5833:     }
1.137     albertel 5834:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5835:     my $ctr=0;
                   5836:     foreach (@$titles) {
                   5837: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5838: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5839: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5840: 	    '>'.$showtitle.'</option>'."\n";
                   5841: 	$ctr++;
                   5842:     }
                   5843:     $result.= '</select>';
                   5844:     return $result;
                   5845: }
                   5846: 
1.495     albertel 5847: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5848:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5849: 
                   5850: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5851: 
1.509     raeburn  5852: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5853:                                    # matchresponse or rankresponse, where 
                   5854:                                    # an individual response can have multiple 
                   5855:                                    # lines
1.503     raeburn  5856: 
                   5857: my %responsetype_per_response;     # responsetype for each response
                   5858: 
1.596.2.12.2.  6(raebur 5859:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5860:3):                                    # numbered response. Needed when randomorder
                   5861:3):                                    # or randompick are in use. Key is ID, value 
                   5862:3):                                    # is response number.
                   5863:3): 
1.495     albertel 5864: # Save and restore the bubble lines array to the form env.
                   5865: 
                   5866: 
                   5867: sub save_bubble_lines {
                   5868:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5869: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5870: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5871: 	    $first_bubble_line{$line};
1.503     raeburn  5872:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5873:             $subdivided_bubble_lines{$line};
                   5874:         $env{"form.scantron.responsetype.$line"} =
                   5875:             $responsetype_per_response{$line};
1.495     albertel 5876:     }
1.596.2.12.2.  6(raebur 5877:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5878:3):         my $line = $masterseq_id_responsenum{$resid};
                   5879:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5880:3):     }
1.495     albertel 5881: }
                   5882: 
                   5883: 
                   5884: sub restore_bubble_lines {
                   5885:     my $line = 0;
                   5886:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5887:3):     %masterseq_id_responsenum = ();
1.495     albertel 5888:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5889: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5890: 	$bubble_lines_per_response{$line} = $value;
                   5891: 	$first_bubble_line{$line}  =
                   5892: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5893:         $subdivided_bubble_lines{$line} =
                   5894:             $env{"form.scantron.sub_bubblelines.$line"};
                   5895:         $responsetype_per_response{$line} =
                   5896:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5897:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5898:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5899: 	$line++;
                   5900:     }
                   5901: }
                   5902: 
1.423     albertel 5903: =pod 
                   5904: 
                   5905: =item scantron_filenames
                   5906: 
                   5907:    Returns a list of the scantron files in the current course 
                   5908: 
                   5909: =cut
1.422     foxr     5910: 
1.202     albertel 5911: sub scantron_filenames {
1.257     albertel 5912:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5913:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5914:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5915:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5916:):                                                         $cname,$getpropath);
1.202     albertel 5917:     my @possiblenames;
1.596.2.12.2.  (raeburn 5918:):     if (ref($dirlist) eq 'ARRAY') {
                   5919:):         foreach my $filename (sort(@{$dirlist})) {
                   5920:): 	    ($filename)=split(/&/,$filename);
                   5921:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5922:): 	    $filename=~s/^scantron_orig_//;
                   5923:): 	    push(@possiblenames,$filename);
                   5924:):         }
1.202     albertel 5925:     }
                   5926:     return @possiblenames;
                   5927: }
                   5928: 
1.423     albertel 5929: =pod 
                   5930: 
                   5931: =item scantron_uploads
                   5932: 
                   5933:    Returns  html drop-down list of scantron files in current course.
                   5934: 
                   5935:  Arguments:
                   5936:    $file2grade - filename to set as selected in the dropdown
                   5937: 
                   5938: =cut
1.422     foxr     5939: 
1.202     albertel 5940: sub scantron_uploads {
1.209     ng       5941:     my ($file2grade) = @_;
1.202     albertel 5942:     my $result=	'<select name="scantron_selectfile">';
                   5943:     $result.="<option></option>";
                   5944:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5945: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5946:     }
                   5947:     $result.="</select>";
                   5948:     return $result;
                   5949: }
                   5950: 
1.423     albertel 5951: =pod 
                   5952: 
                   5953: =item scantron_scantab
                   5954: 
                   5955:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5956:   file.
                   5957: 
                   5958: =cut
1.422     foxr     5959: 
1.82      albertel 5960: sub scantron_scantab {
                   5961:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5962:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 5963:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5964:     if (@lines > 0) {
                   5965:         foreach my $line (@lines) {
                   5966:             next if (($line =~ /^\#/) || ($line eq ''));
                   5967: 	    my ($name,$descrip)=split(/:/,$line);
                   5968: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5969:         }
1.82      albertel 5970:     }
                   5971:     $result.='</select>'."\n";
1.518     raeburn  5972:     return $result;
                   5973: }
                   5974: 
1.423     albertel 5975: =pod 
                   5976: 
                   5977: =item scantron_CODElist
                   5978: 
                   5979:   Returns html drop down of the saved CODE lists from current course,
                   5980:   generated from earlier printings.
                   5981: 
                   5982: =cut
1.422     foxr     5983: 
1.186     albertel 5984: sub scantron_CODElist {
1.257     albertel 5985:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5986:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5987:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5988:     my $namechoice='<option></option>';
1.225     albertel 5989:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5990: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5991: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5992: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5993:     }
                   5994:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5995:     return $namechoice;
                   5996: }
                   5997: 
1.423     albertel 5998: =pod 
                   5999: 
                   6000: =item scantron_CODEunique
                   6001: 
                   6002:   Returns the html for "Each CODE to be used once" radio.
                   6003: 
                   6004: =cut
1.422     foxr     6005: 
1.186     albertel 6006: sub scantron_CODEunique {
1.532     bisitz   6007:     my $result='<span class="LC_nobreak">
1.272     albertel 6008:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6009:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6010:                 </span>
1.532     bisitz   6011:                 <span class="LC_nobreak">
1.272     albertel 6012:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6013:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6014:                 </span>';
1.186     albertel 6015:     return $result;
                   6016: }
1.423     albertel 6017: 
                   6018: =pod 
                   6019: 
                   6020: =item scantron_selectphase
                   6021: 
1.596.2.6  raeburn  6022:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6023:   Allows for - starting a grading run.
1.424     albertel 6024:              - downloading existing scan data (original, corrected
1.423     albertel 6025:                                                 or skipped info)
                   6026: 
                   6027:              - uploading new scan data
                   6028: 
                   6029:  Arguments:
                   6030:   $r          - The Apache request object
                   6031:   $file2grade - name of the file that contain the scanned data to score
                   6032: 
                   6033: =cut
1.186     albertel 6034: 
1.75      albertel 6035: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6036:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6037:     if (!$symb) {return '';}
1.582     raeburn  6038:     my $map_error;
                   6039:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6040:     if ($map_error) {
                   6041:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6042:         return;
                   6043:     }
1.324     albertel 6044:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6045:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6046:     my $format_selector=&scantron_scantab();
1.186     albertel 6047:     my $CODE_selector=&scantron_CODElist();
                   6048:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6049:     my $result;
1.422     foxr     6050: 
1.513     foxr     6051:     $ssi_error = 0;
                   6052: 
1.596.2.4  raeburn  6053:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6054:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6055: 
                   6056:         # Chunk of form to prompt for a scantron file upload.
                   6057: 
                   6058:         $r->print('
1.596.2.12.2.  9(raebur 6059:9):     <br />');
                   6060:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6061:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6062:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6063:9):         &js_escape(\$alertmsg);
                   6064:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6065:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6066:     function checkUpload(formname) {
                   6067:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6068:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6069:             return false;
                   6070:         }
                   6071:         formname.submit();
1.596.2.12.2.  9(raebur 6072:9):     }'."\n".$formatjs));
                   6073:9):         $r->print('
1.596.2.4  raeburn  6074:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6075:                 '.$default_form_data.'
                   6076:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6077:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6078:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6079:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6080:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6081:9):                 <th>
                   6082:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6083:9):                 </th>
                   6084:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6085:9):               '.&Apache::loncommon::start_data_table_row().'
                   6086:9):             <td>
                   6087:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6088:9):         if ($formatoptions) {
                   6089:9):             $r->print('</td>
                   6090:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6091:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6092:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6093:9):                  </td>
                   6094:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6095:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6096:9):                  <td>'
                   6097:9):             );
                   6098:9):         } else {
                   6099:9):             $r->print(' <br />');
                   6100:9):         }
                   6101:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6102:9):               </td>
                   6103:9):              '.&Apache::loncommon::end_data_table_row().'
                   6104:9):              '.&Apache::loncommon::end_data_table().'
                   6105:9):              </form>'
                   6106:9):         );
1.596.2.4  raeburn  6107: 
                   6108:     }
                   6109: 
1.422     foxr     6110:     # Chunk of form to prompt for a file to grade and how:
                   6111: 
1.489     albertel 6112:     $result.= '
                   6113:     <br />
                   6114:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6115:     <input type="hidden" name="command" value="scantron_warning" />
                   6116:     '.$default_form_data.'
                   6117:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6118:        '.&Apache::loncommon::start_data_table_header_row().'
                   6119:             <th colspan="2">
1.492     albertel 6120:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6121:             </th>
                   6122:        '.&Apache::loncommon::end_data_table_header_row().'
                   6123:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6124:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6125:        '.&Apache::loncommon::end_data_table_row().'
                   6126:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6127:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6128:        '.&Apache::loncommon::end_data_table_row().'
                   6129:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6130:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6131:        '.&Apache::loncommon::end_data_table_row().'
                   6132:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6133:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6134:        '.&Apache::loncommon::end_data_table_row().'
                   6135:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6136:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6137:        '.&Apache::loncommon::end_data_table_row().'
                   6138:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6139: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6140:             <td>
1.492     albertel 6141: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6142:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6143:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6144: 	    </td>
1.489     albertel 6145:        '.&Apache::loncommon::end_data_table_row().'
                   6146:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6147:             <td colspan="2">
1.572     www      6148:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6149:             </td>
1.489     albertel 6150:        '.&Apache::loncommon::end_data_table_row().'
                   6151:     '.&Apache::loncommon::end_data_table().'
                   6152:     </form>
                   6153: ';
1.162     albertel 6154:    
                   6155:     $r->print($result);
                   6156: 
1.422     foxr     6157:     # Chunk of the form that prompts to view a scoring office file,
                   6158:     # corrected file, skipped records in a file.
                   6159: 
1.489     albertel 6160:     $r->print('
                   6161:    <br />
                   6162:    <form action="/adm/grades" name="scantron_download">
                   6163:      '.$default_form_data.'
                   6164:      <input type="hidden" name="command" value="scantron_download" />
                   6165:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6166:        '.&Apache::loncommon::start_data_table_header_row().'
                   6167:               <th>
1.492     albertel 6168:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6169:               </th>
                   6170:        '.&Apache::loncommon::end_data_table_header_row().'
                   6171:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6172:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6173:                 <br />
1.492     albertel 6174:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6175:        '.&Apache::loncommon::end_data_table_row().'
                   6176:      '.&Apache::loncommon::end_data_table().'
                   6177:    </form>
                   6178:    <br />
                   6179: ');
1.162     albertel 6180: 
1.457     banghart 6181:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6182: 
1.596.2.12.2.  8(raebur 6183:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6184:              $default_form_data."\n".
                   6185:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6186:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6187:              '<th colspan="2">
1.572     www      6188:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6189:              '</th>'."\n".
                   6190:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6191:               &Apache::loncommon::start_data_table_row()."\n".
                   6192:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6193:               '<td> '.$sequence_selector.' </td>'.
                   6194:               &Apache::loncommon::end_data_table_row()."\n".
                   6195:               &Apache::loncommon::start_data_table_row()."\n".
                   6196:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6197:               '<td> '.$file_selector.' </td>'."\n".
                   6198:               &Apache::loncommon::end_data_table_row()."\n".
                   6199:               &Apache::loncommon::start_data_table_row()."\n".
                   6200:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6201:               '<td> '.$format_selector.' </td>'."\n".
                   6202:               &Apache::loncommon::end_data_table_row()."\n".
                   6203:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6204:               '<td> '.&mt('Options').' </td>'."\n".
                   6205:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6206:               &Apache::loncommon::end_data_table_row()."\n".
                   6207:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6208:               '<td colspan="2">'."\n".
                   6209:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6210:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6211:               '</td>'."\n".
                   6212:               &Apache::loncommon::end_data_table_row()."\n".
                   6213:               &Apache::loncommon::end_data_table()."\n".
                   6214:               '</form><br />');
                   6215:     return;
1.75      albertel 6216: }
                   6217: 
1.423     albertel 6218: =pod 
                   6219: 
                   6220: =item username_to_idmap
                   6221: 
1.556     weissno  6222:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6223:     student username:domain.
                   6224: 
                   6225:   Arguments:
                   6226: 
                   6227:     $classlist - reference to the class list hash. This is a hash
                   6228:                  keyed by student name:domain  whose elements are references
1.424     albertel 6229:                  to arrays containing various chunks of information
1.423     albertel 6230:                  about the student. (See loncoursedata for more info).
                   6231: 
                   6232:   Returns
                   6233:     %idmap - the constructed hash
                   6234: 
                   6235: =cut
                   6236: 
1.82      albertel 6237: sub username_to_idmap {
                   6238:     my ($classlist)= @_;
                   6239:     my %idmap;
                   6240:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6241:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6242:5):         unless ($id eq '') {
                   6243:5):             if (!exists($idmap{$id})) {
                   6244:5):                 $idmap{$id} = $student;
                   6245:5):             } else {
                   6246:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6247:5):                 if ($status eq 'Active') {
                   6248:5):                     $idmap{$id} = $student;
                   6249:5):                 }
                   6250:5):             }
                   6251:5):         }
1.82      albertel 6252:     }
                   6253:     return %idmap;
                   6254: }
1.423     albertel 6255: 
                   6256: =pod
                   6257: 
1.424     albertel 6258: =item scantron_fixup_scanline
1.423     albertel 6259: 
                   6260:    Process a requested correction to a scanline.
                   6261: 
                   6262:   Arguments:
1.596.2.12.2.  9(raebur 6263:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6264:     $scan_data         - hash of correction information 
                   6265:                           (see &scantron_getfile())
                   6266:     $line              - existing scanline
                   6267:     $whichline         - line number of the passed in scanline
                   6268:     $field             - type of change to process 
                   6269:                          (either 
1.573     bisitz   6270:                           'ID'     -> correct the student/employee ID
1.423     albertel 6271:                           'CODE'   -> correct the CODE
                   6272:                           'answer' -> fixup the submitted answers)
                   6273:     
                   6274:    $args               - hash of additional info,
                   6275:                           - 'ID' 
                   6276:                                'newid' -> studentID to use in replacement
1.424     albertel 6277:                                           of existing one
1.423     albertel 6278:                           - 'CODE' 
                   6279:                                'CODE_ignore_dup' - set to true if duplicates
                   6280:                                                    should be ignored.
                   6281: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6282:                                         if the existing unfound code should
1.423     albertel 6283:                                         be used as is
                   6284:                           - 'answer'
                   6285:                                'response' - new answer or 'none' if blank
                   6286:                                'question' - the bubble line to change
1.503     raeburn  6287:                                'questionnum' - the question identifier,
                   6288:                                                may include subquestion. 
1.423     albertel 6289: 
                   6290:   Returns:
                   6291:     $line - the modified scanline
                   6292: 
                   6293:   Side effects: 
                   6294:     $scan_data - may be updated
                   6295: 
                   6296: =cut
                   6297: 
1.82      albertel 6298: 
1.157     albertel 6299: sub scantron_fixup_scanline {
                   6300:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6301:     if ($field eq 'ID') {
                   6302: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6303: 	    return ($line,1,'New value too large');
1.157     albertel 6304: 	}
                   6305: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6306: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6307: 				     $args->{'newid'});
                   6308: 	}
                   6309: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6310: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6311: 	if ($args->{'newid'}=~/^\s*$/) {
                   6312: 	    &scan_data($scan_data,"$whichline.user",
                   6313: 		       $args->{'username'}.':'.$args->{'domain'});
                   6314: 	}
1.186     albertel 6315:     } elsif ($field eq 'CODE') {
1.192     albertel 6316: 	if ($args->{'CODE_ignore_dup'}) {
                   6317: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6318: 	}
                   6319: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6320: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6321: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6322: 		return ($line,1,'New CODE value too large');
                   6323: 	    }
                   6324: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6325: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6326: 	    }
                   6327: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6328: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6329: 	}
1.157     albertel 6330:     } elsif ($field eq 'answer') {
1.497     foxr     6331: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6332: 	my $off=$scantron_config->{'Qoff'};
                   6333: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6334: 	my $answer=${off}x$length;
                   6335: 	if ($args->{'response'} eq 'none') {
                   6336: 	    &scan_data($scan_data,
1.503     raeburn  6337: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6338: 	} else {
                   6339: 	    if ($on eq 'letter') {
                   6340: 		my @alphabet=('A'..'Z');
                   6341: 		$answer=$alphabet[$args->{'response'}];
                   6342: 	    } elsif ($on eq 'number') {
                   6343: 		$answer=$args->{'response'}+1;
                   6344: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6345: 	    } else {
1.497     foxr     6346: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6347: 	    }
1.497     foxr     6348: 	    &scan_data($scan_data,
1.503     raeburn  6349: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6350: 	}
1.497     foxr     6351: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6352: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6353:     }
                   6354:     return $line;
                   6355: }
1.423     albertel 6356: 
                   6357: =pod
                   6358: 
                   6359: =item scan_data
                   6360: 
                   6361:     Edit or look up  an item in the scan_data hash.
                   6362: 
                   6363:   Arguments:
                   6364:     $scan_data  - The hash (see scantron_getfile)
                   6365:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6366:                   scantronfilename_key).
1.423     albertel 6367:     $data        - New value of the hash entry.
                   6368:     $delete      - If true, the entry is removed from the hash.
                   6369: 
                   6370:   Returns:
                   6371:     The new value of the hash table field (undefined if deleted).
                   6372: 
                   6373: =cut
                   6374: 
                   6375: 
1.157     albertel 6376: sub scan_data {
                   6377:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6378:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6379:     if (defined($value)) {
                   6380: 	$scan_data->{$filename.'_'.$key} = $value;
                   6381:     }
                   6382:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6383:     return $scan_data->{$filename.'_'.$key};
                   6384: }
1.423     albertel 6385: 
1.495     albertel 6386: # ----- These first few routines are general use routines.----
                   6387: 
                   6388: # Return the number of occurences of a pattern in a string.
                   6389: 
                   6390: sub occurence_count {
                   6391:     my ($string, $pattern) = @_;
                   6392: 
                   6393:     my @matches = ($string =~ /$pattern/g);
                   6394: 
                   6395:     return scalar(@matches);
                   6396: }
                   6397: 
                   6398: 
                   6399: # Take a string known to have digits and convert all the
                   6400: # digits into letters in the range J,A..I.
                   6401: 
                   6402: sub digits_to_letters {
                   6403:     my ($input) = @_;
                   6404: 
                   6405:     my @alphabet = ('J', 'A'..'I');
                   6406: 
                   6407:     my @input    = split(//, $input);
                   6408:     my $output ='';
                   6409:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6410: 	if ($input[$i] =~ /\d/) {
                   6411: 	    $output .= $alphabet[$input[$i]];
                   6412: 	} else {
                   6413: 	    $output .= $input[$i];
                   6414: 	}
                   6415:     }
                   6416:     return $output;
                   6417: }
                   6418: 
1.423     albertel 6419: =pod 
                   6420: 
                   6421: =item scantron_parse_scanline
                   6422: 
                   6423:   Decodes a scanline from the selected scantron file
                   6424: 
                   6425:  Arguments:
                   6426:     line             - The text of the scantron file line to process
                   6427:     whichline        - Line number
                   6428:     scantron_config  - Hash describing the format of the scantron lines.
                   6429:     scan_data        - Hash of extra information about the scanline
                   6430:                        (see scantron_getfile for more information)
                   6431:     just_header      - True if should not process question answers but only
                   6432:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6433:3):     randomorder      - True if randomorder in use
                   6434:3):     randompick       - True if randompick in use
                   6435:3):     sequence         - Exam folder URL
                   6436:3):     master_seq       - Ref to array containing symbs in exam folder
                   6437:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6438:3):                        (corresponding values are resource objects)
                   6439:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6440:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6441:3):                        are refs to an array of resource objects, ordered
                   6442:3):                        according to order used for CODE, when randomorder
                   6443:3):                        and or randompick are in use.
                   6444:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6445:3):                        for current line to question number used for same question
                   6446:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6447:3):     startline        - Ref to hash where key is question number (0 is first)
                   6448:3):                        and value is number of first bubble line for current 
                   6449:3):                        student or code-based randompick and/or randomorder.
                   6450:3):     totalref         - Ref of scalar used to score total number of bubble
                   6451:3):                        lines needed for responses in a scan line (used when
                   6452:3):                        randompick in use. 
                   6453:3): 
1.423     albertel 6454:  Returns:
                   6455:    Hash containing the result of parsing the scanline
                   6456: 
                   6457:    Keys are all proceeded by the string 'scantron.'
                   6458: 
                   6459:        CODE    - the CODE in use for this scanline
                   6460:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6461:                  by the operator
                   6462:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6463:                             CODEs were selected, but the usage has been
                   6464:                             forced by the operator
1.556     weissno  6465:        ID  - student/employee ID
1.423     albertel 6466:        PaperID - if used, the ID number printed on the sheet when the 
                   6467:                  paper was scanned
                   6468:        FirstName - first name from the sheet
                   6469:        LastName  - last name from the sheet
                   6470: 
                   6471:      if just_header was not true these key may also exist
                   6472: 
1.447     foxr     6473:        missingerror - a list of bubble ranges that are considered to be answers
                   6474:                       to a single question that don't have any bubbles filled in.
                   6475:                       Of the form questionnumber:firstbubblenumber:count.
                   6476:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6477:                       to a single question that have more than one bubble filled in.
                   6478:                       Of the form questionnumber::firstbubblenumber:count
                   6479:    
                   6480:                 In the above, count is the number of bubble responses in the
                   6481:                 input line needed to represent the possible answers to the question.
                   6482:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6483:                 per line would have count = 2.
                   6484: 
1.423     albertel 6485:        maxquest     - the number of the last bubble line that was parsed
                   6486: 
                   6487:        (<number> starts at 1)
                   6488:        <number>.answer - zero or more letters representing the selected
                   6489:                          letters from the scanline for the bubble line 
                   6490:                          <number>.
                   6491:                          if blank there was either no bubble or there where
                   6492:                          multiple bubbles, (consult the keys missingerror and
                   6493:                          doubleerror if this is an error condition)
                   6494: 
                   6495: =cut
                   6496: 
1.82      albertel 6497: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6498:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6499:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6500:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6501: 
1.82      albertel 6502:     my %record;
1.596.2.12.2.  6(raebur 6503:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6504:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6505: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6506: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6507: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6508: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6509: 	    $record{'scantron.CODE'}=substr($data,
                   6510: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6511: 					    $$scantron_config{'CODElength'});
1.191     albertel 6512: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6513: 		$record{'scantron.useCODE'}=1;
                   6514: 	    }
1.192     albertel 6515: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6516: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6517: 	    }
1.82      albertel 6518: 	} else {
                   6519: 	    #FIXME interpret first N questions
                   6520: 	}
                   6521:     }
1.83      albertel 6522:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6523: 				  $$scantron_config{'IDlength'});
1.157     albertel 6524:     $record{'scantron.PaperID'}=
                   6525: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6526: 	       $$scantron_config{'PaperIDlength'});
                   6527:     $record{'scantron.FirstName'}=
                   6528: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6529: 	       $$scantron_config{'FirstNamelength'});
                   6530:     $record{'scantron.LastName'}=
                   6531: 	substr($data,$$scantron_config{'LastName'}-1,
                   6532: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6533:     if ($just_header) { return \%record; }
1.194     albertel 6534: 
1.82      albertel 6535:     my @alphabet=('A'..'Z');
                   6536:     my $questnum=0;
1.447     foxr     6537:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6538: 
1.596.2.12.2.  6(raebur 6539:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6540:3):     if ($randompick || $randomorder) {
                   6541:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6542:3):                                          $master_seq,$symb_to_resource,
                   6543:3):                                          $partids_by_symb,$orderedforcode,
                   6544:3):                                          $respnumlookup,$startline);
                   6545:3):         if ($total) {
                   6546:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6547:3):         }
                   6548:3):         if (ref($totalref)) {
                   6549:3):             $$totalref = $total;
                   6550:3):         }
                   6551:3):     }
                   6552:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6553:     chomp($questions);		# Get rid of any trailing \n.
                   6554:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6555:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6556:3):         my $answers_needed;
                   6557:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6558:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6559:3):         } else {
                   6560:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6561:3):         }
1.503     raeburn  6562:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6563:                              || 1;
                   6564:         $questnum++;
                   6565:         my $quest_id = $questnum;
                   6566:         my $currentquest = substr($questions,0,$answer_length);
                   6567:         $questions       = substr($questions,$answer_length);
                   6568:         if (length($currentquest) < $answer_length) { next; }
                   6569: 
1.596.2.12.2.  6(raebur 6570:3):         my $subdivided;
                   6571:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6572:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6573:3):         } else {
                   6574:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6575:3):         }
                   6576:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6577:             my $subquestnum = 1;
                   6578:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6579:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6580:             foreach my $subans (@subanswers_needed) {
                   6581:                 my $subans_length =
                   6582:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6583:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6584:                 $subquestions   = substr($subquestions,$subans_length);
                   6585:                 $quest_id = "$questnum.$subquestnum";
                   6586:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6587:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6588:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6589:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6590:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6591:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6592:                 } else {
                   6593:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6594:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6595:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6596:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6597:                 }
                   6598:                 $subquestnum ++;
                   6599:             }
                   6600:         } else {
                   6601:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6602:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6603:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6604:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6605:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6606:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6607:             } else {
                   6608:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6609:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6610:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6611:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6612:             }
                   6613:         }
                   6614:     }
                   6615:     $record{'scantron.maxquest'}=$questnum;
                   6616:     return \%record;
                   6617: }
1.447     foxr     6618: 
1.596.2.12.2.  6(raebur 6619:3): sub get_master_seq {
                   6620:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6621:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6622:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6623:3):     my $resource_error;
                   6624:3):     foreach my $resource (@{$resources}) {
                   6625:3):         my $ressymb;
                   6626:3):         if (ref($resource)) {
                   6627:3):             $ressymb = $resource->symb();
                   6628:3):             push(@{$master_seq},$ressymb);
                   6629:3):             $symb_to_resource->{$ressymb} = $resource;
                   6630:3):         } else {
                   6631:3):             $resource_error = 1;
                   6632:3):             last;
                   6633:3):         }
                   6634:3):     }
                   6635:3):     return $resource_error;
                   6636:3): }
                   6637:3): 
                   6638:3): sub get_respnum_lookups {
                   6639:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6640:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6641:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6642:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6643:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6644:3):                    (ref($startline) eq 'HASH'));
                   6645:3):     my ($user,$scancode);
                   6646:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6647:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6648:3):         $scancode = $record->{'scantron.CODE'};
                   6649:3):     } else {
                   6650:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6651:3):     }
                   6652:3):     my @mapresources =
                   6653:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6654:3):                      $orderedforcode);
                   6655:3):     my $total = 0;
                   6656:3):     my $count = 0;
                   6657:3):     foreach my $resource (@mapresources) {
                   6658:3):         my $id = $resource->id();
                   6659:3):         my $symb = $resource->symb();
                   6660:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6661:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6662:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6663:3):                 if ($respnum ne '') {
                   6664:3):                     $respnumlookup->{$count} = $respnum;
                   6665:3):                     $startline->{$count} = $total;
                   6666:3):                     $total += $bubble_lines_per_response{$respnum};
                   6667:3):                     $count ++;
                   6668:3):                 }
                   6669:3):             }
                   6670:3):         }
                   6671:3):     }
                   6672:3):     return $total;
                   6673:3): }
                   6674:3): 
1.503     raeburn  6675: sub scantron_validator_lettnum {
                   6676:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6677:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6678:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6679: 
                   6680:     # Qon 'letter' implies for each slot in currquest we have:
                   6681:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6682:     #    about anything else (esp. a value of Qoff) for missing
                   6683:     #    bubbles.
                   6684:     #
                   6685:     # Qon 'number' implies each slot gives a digit that indexes the
                   6686:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6687:     #    and * or ? for double bubbles on a single line.
                   6688:     #
1.447     foxr     6689: 
1.503     raeburn  6690:     my $matchon;
                   6691:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6692:         $matchon = '[A-Z]';
                   6693:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6694:         $matchon = '\d';
                   6695:     }
                   6696:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6697:3):     my $responsenum = $questnum-1;
                   6698:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6699:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6700:3):     }
                   6701:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6702:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6703:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6704:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6705:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6706:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6707:         my @singlelines = split('',$currquest);
                   6708:         foreach my $entry (@singlelines) {
                   6709:             $occurrences = &occurence_count($entry,$matchon);
                   6710:             if ($occurrences > 1) {
                   6711:                 last;
                   6712:             }
1.596.2.12.2.  6(raebur 6713:3):         }
1.503     raeburn  6714:     } else {
                   6715:         $occurrences = &occurence_count($currquest,$matchon); 
                   6716:     }
                   6717:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6718:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6719:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6720:             my $bubble = substr($currquest,$ans,1);
                   6721:             if ($bubble =~ /$matchon/ ) {
                   6722:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6723:                     if ($bubble == 0) {
                   6724:                         $bubble = 10; 
                   6725:                     }
                   6726:                     $record->{"scantron.$ansnum.answer"} = 
                   6727:                         $alphabet->[$bubble-1];
                   6728:                 } else {
                   6729:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6730:                 }
                   6731:             } else {
                   6732:                 $record->{"scantron.$ansnum.answer"}='';
                   6733:             }
                   6734:             $ansnum++;
                   6735:         }
                   6736:     } elsif (!defined($currquest)
                   6737:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6738:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6739:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6740:             $record->{"scantron.$ansnum.answer"}='';
                   6741:             $ansnum++;
                   6742:         }
                   6743:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6744:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6745:         }
                   6746:     } else {
                   6747:         if ($$scantron_config{'Qon'} eq 'number') {
                   6748:             $currquest = &digits_to_letters($currquest);            
                   6749:         }
                   6750:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6751:             my $bubble = substr($currquest,$ans,1);
                   6752:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6753:             $ansnum++;
                   6754:         }
                   6755:     }
                   6756:     return $ansnum;
                   6757: }
1.447     foxr     6758: 
1.503     raeburn  6759: sub scantron_validator_positional {
                   6760:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6761:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6762:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6763: 
1.503     raeburn  6764:     # Otherwise there's a positional notation;
                   6765:     # each bubble line requires Qlength items, and there are filled in
                   6766:     # bubbles for each case where there 'Qon' characters.
                   6767:     #
1.447     foxr     6768: 
1.503     raeburn  6769:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6770: 
1.503     raeburn  6771:     # If the split only gives us one element.. the full length of the
                   6772:     # answer string, no bubbles are filled in:
1.447     foxr     6773: 
1.507     raeburn  6774:     if ($answers_needed eq '') {
                   6775:         return;
                   6776:     }
                   6777: 
1.503     raeburn  6778:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6779:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6780:             $record->{"scantron.$ansnum.answer"}='';
                   6781:             $ansnum++;
                   6782:         }
                   6783:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6784:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6785:         }
                   6786:     } elsif (scalar(@array) == 2) {
                   6787:         my $location = length($array[0]);
                   6788:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6789:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6790:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6791:             if ($ans eq $line_num) {
                   6792:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6793:             } else {
                   6794:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6795:             }
                   6796:             $ansnum++;
                   6797:          }
                   6798:     } else {
                   6799:         #  If there's more than one instance of a bubble character
                   6800:         #  That's a double bubble; with positional notation we can
                   6801:         #  record all the bubbles filled in as well as the
                   6802:         #  fact this response consists of multiple bubbles.
                   6803:         #
1.596.2.12.2.  6(raebur 6804:3):         my $responsenum = $questnum-1;
                   6805:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6806:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6807:3):         }
                   6808:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6809:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6810:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6811:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6812:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6813:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6814:             my $doubleerror = 0;
                   6815:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6816:                    (!$doubleerror)) {
                   6817:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6818:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6819:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6820:                if (length(@currarray) > 2) {
                   6821:                    $doubleerror = 1;
                   6822:                } 
                   6823:             }
                   6824:             if ($doubleerror) {
                   6825:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6826:             }
                   6827:         } else {
                   6828:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6829:         }
                   6830:         my $item = $ansnum;
                   6831:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6832:             $record->{"scantron.$item.answer"} = '';
                   6833:             $item ++;
                   6834:         }
1.447     foxr     6835: 
1.503     raeburn  6836:         my @ans=@array;
                   6837:         my $i=0;
                   6838:         my $increment = 0;
                   6839:         while ($#ans) {
                   6840:             $i+=length($ans[0]) + $increment;
                   6841:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6842:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6843:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6844:             shift(@ans);
                   6845:             $increment = 1;
                   6846:         }
                   6847:         $ansnum += $answers_needed;
1.82      albertel 6848:     }
1.503     raeburn  6849:     return $ansnum;
1.82      albertel 6850: }
                   6851: 
1.423     albertel 6852: =pod
                   6853: 
                   6854: =item scantron_add_delay
                   6855: 
                   6856:    Adds an error message that occurred during the grading phase to a
                   6857:    queue of messages to be shown after grading pass is complete
                   6858: 
                   6859:  Arguments:
1.424     albertel 6860:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6861:    $scanline    - the scanline that caused the error
                   6862:    $errormesage - the error message
                   6863:    $errorcode   - a numeric code for the error
                   6864: 
                   6865:  Side Effects:
1.424     albertel 6866:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6867: 
                   6868: =cut
                   6869: 
1.82      albertel 6870: sub scantron_add_delay {
1.140     albertel 6871:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6872:     push(@$delayqueue,
                   6873: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6874: 	  'ecode' => $errorcode }
                   6875: 	 );
1.82      albertel 6876: }
                   6877: 
1.423     albertel 6878: =pod
                   6879: 
                   6880: =item scantron_find_student
                   6881: 
1.424     albertel 6882:    Finds the username for the current scanline
                   6883: 
                   6884:   Arguments:
                   6885:    $scantron_record - hash result from scantron_parse_scanline
                   6886:    $scan_data       - hash of correction information 
                   6887:                       (see &scantron_getfile() form more information)
                   6888:    $idmap           - hash from &username_to_idmap()
                   6889:    $line            - number of current scanline
                   6890:  
                   6891:   Returns:
                   6892:    Either 'username:domain' or undef if unknown
                   6893: 
1.423     albertel 6894: =cut
                   6895: 
1.82      albertel 6896: sub scantron_find_student {
1.157     albertel 6897:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6898:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6899:     if ($scanID =~ /^\s*$/) {
                   6900:  	return &scan_data($scan_data,"$line.user");
                   6901:     }
1.83      albertel 6902:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6903:  	if (lc($id) eq lc($scanID)) {
                   6904:  	    return $$idmap{$id};
                   6905:  	}
1.83      albertel 6906:     }
                   6907:     return undef;
                   6908: }
                   6909: 
1.423     albertel 6910: =pod
                   6911: 
                   6912: =item scantron_filter
                   6913: 
1.424     albertel 6914:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6915:    hidden resources was selected
                   6916: 
1.423     albertel 6917: =cut
                   6918: 
1.83      albertel 6919: sub scantron_filter {
                   6920:     my ($curres)=@_;
1.331     albertel 6921: 
                   6922:     if (ref($curres) && $curres->is_problem()) {
                   6923: 	# if the user has asked to not have either hidden
                   6924: 	# or 'randomout' controlled resources to be graded
                   6925: 	# don't include them
                   6926: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6927: 	    && $curres->randomout) {
                   6928: 	    return 0;
                   6929: 	}
1.83      albertel 6930: 	return 1;
                   6931:     }
                   6932:     return 0;
1.82      albertel 6933: }
                   6934: 
1.423     albertel 6935: =pod
                   6936: 
                   6937: =item scantron_process_corrections
                   6938: 
1.424     albertel 6939:    Gets correction information out of submitted form data and corrects
                   6940:    the scanline
                   6941: 
1.423     albertel 6942: =cut
                   6943: 
1.157     albertel 6944: sub scantron_process_corrections {
                   6945:     my ($r) = @_;
1.596.2.12.2.  9(raebur 6946:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6947:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6948:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6949:     my $which=$env{'form.scantron_line'};
1.200     albertel 6950:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6951:     my ($skip,$err,$errmsg);
1.257     albertel 6952:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6953: 	$skip=1;
1.257     albertel 6954:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6955: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6956: 	    $env{'form.scantron_domain'};
1.157     albertel 6957: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6958: 	($line,$err,$errmsg)=
                   6959: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6960: 				     'ID',{'newid'=>$newid,
1.257     albertel 6961: 				    'username'=>$env{'form.scantron_username'},
                   6962: 				    'domain'=>$env{'form.scantron_domain'}});
                   6963:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6964: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6965: 	my $newCODE;
1.192     albertel 6966: 	my %args;
1.190     albertel 6967: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6968: 	    $newCODE='use_unfound';
1.190     albertel 6969: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6970: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6971: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6972: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6973: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6974: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6975: 	}
1.257     albertel 6976: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6977: 	    $args{'CODE_ignore_dup'}=1;
                   6978: 	}
                   6979: 	$args{'CODE'}=$newCODE;
1.186     albertel 6980: 	($line,$err,$errmsg)=
                   6981: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6982: 				     'CODE',\%args);
1.257     albertel 6983:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6984: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6985: 	    ($line,$err,$errmsg)=
                   6986: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6987: 					 $which,'answer',
                   6988: 					 { 'question'=>$question,
1.503     raeburn  6989: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6990:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6991: 	    if ($err) { last; }
                   6992: 	}
                   6993:     }
                   6994:     if ($err) {
1.596.2.12.2.  0(raebur 6995:3): 	$r->print(
                   6996:3):             '<p class="LC_error">'
                   6997:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6998:3):                 $errmsg)
          1(raebur 6999:3):            .'</p>');
1.157     albertel 7000:     } else {
1.200     albertel 7001: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7002: 	&scantron_putfile($scanlines,$scan_data);
                   7003:     }
                   7004: }
                   7005: 
1.423     albertel 7006: =pod
                   7007: 
                   7008: =item reset_skipping_status
                   7009: 
1.424     albertel 7010:    Forgets the current set of remember skipped scanlines (and thus
                   7011:    reverts back to considering all lines in the
                   7012:    scantron_skipped_<filename> file)
                   7013: 
1.423     albertel 7014: =cut
                   7015: 
1.200     albertel 7016: sub reset_skipping_status {
                   7017:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7018:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7019:     &scantron_putfile(undef,$scan_data);
                   7020: }
                   7021: 
1.423     albertel 7022: =pod
                   7023: 
                   7024: =item start_skipping
                   7025: 
1.424     albertel 7026:    Marks a scanline to be skipped. 
                   7027: 
1.423     albertel 7028: =cut
                   7029: 
1.376     albertel 7030: sub start_skipping {
1.200     albertel 7031:     my ($scan_data,$i)=@_;
                   7032:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7033:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7034: 	$remembered{$i}=2;
                   7035:     } else {
                   7036: 	$remembered{$i}=1;
                   7037:     }
1.200     albertel 7038:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7039: }
                   7040: 
1.423     albertel 7041: =pod
                   7042: 
                   7043: =item should_be_skipped
                   7044: 
1.424     albertel 7045:    Checks whether a scanline should be skipped.
                   7046: 
1.423     albertel 7047: =cut
                   7048: 
1.200     albertel 7049: sub should_be_skipped {
1.376     albertel 7050:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7051:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7052: 	# not redoing old skips
1.376     albertel 7053: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7054: 	return 0;
                   7055:     }
                   7056:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7057: 
                   7058:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7059: 	return 0;
                   7060:     }
1.200     albertel 7061:     return 1;
                   7062: }
                   7063: 
1.423     albertel 7064: =pod
                   7065: 
                   7066: =item remember_current_skipped
                   7067: 
1.424     albertel 7068:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7069:    file and remembers them into scan_data for later use.
                   7070: 
1.423     albertel 7071: =cut
                   7072: 
1.200     albertel 7073: sub remember_current_skipped {
                   7074:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7075:     my %to_remember;
                   7076:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7077: 	if ($scanlines->{'skipped'}[$i]) {
                   7078: 	    $to_remember{$i}=1;
                   7079: 	}
                   7080:     }
1.376     albertel 7081: 
1.200     albertel 7082:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7083:     &scantron_putfile(undef,$scan_data);
                   7084: }
                   7085: 
1.423     albertel 7086: =pod
                   7087: 
                   7088: =item check_for_error
                   7089: 
1.424     albertel 7090:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7091:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7092:     something went wrong.
                   7093: 
1.423     albertel 7094: =cut
                   7095: 
1.200     albertel 7096: sub check_for_error {
                   7097:     my ($r,$result)=@_;
                   7098:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7099: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7100:     }
                   7101: }
1.157     albertel 7102: 
1.423     albertel 7103: =pod
                   7104: 
                   7105: =item scantron_warning_screen
                   7106: 
1.424     albertel 7107:    Interstitial screen to make sure the operator has selected the
                   7108:    correct options before we start the validation phase.
                   7109: 
1.423     albertel 7110: =cut
                   7111: 
1.203     albertel 7112: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7113:0):     my ($button_text,$symb)=@_;
1.257     albertel 7114:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7115:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7116:     my $CODElist;
1.284     albertel 7117:     if ($scantron_config{'CODElocation'} &&
                   7118: 	$scantron_config{'CODEstart'} &&
                   7119: 	$scantron_config{'CODElength'}) {
                   7120: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7121:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7122: 	$CODElist=
1.492     albertel 7123: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7124: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7125:     }
1.596.2.12.2.  (raeburn 7126:):     my $lastbubblepoints;
                   7127:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7128:):         $lastbubblepoints =
                   7129:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7130:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7131:):     }
1.492     albertel 7132:     return ('
1.203     albertel 7133: <p>
1.492     albertel 7134: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7135:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7136: </p>
                   7137: <table>
1.492     albertel 7138: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7139: <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 7140:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7141: </table>
1.596.2.12.2.  1(raebur 7142:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7143: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 7144: 
                   7145: <br />
1.492     albertel 7146: ');
1.203     albertel 7147: }
                   7148: 
1.423     albertel 7149: =pod
                   7150: 
                   7151: =item scantron_do_warning
                   7152: 
1.424     albertel 7153:    Check if the operator has picked something for all required
                   7154:    fields. Error out if something is missing.
                   7155: 
1.423     albertel 7156: =cut
                   7157: 
1.203     albertel 7158: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7159:0):     my ($r,$symb)=@_;
1.203     albertel 7160:     if (!$symb) {return '';}
1.324     albertel 7161:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7162:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7163:     if ( $env{'form.selectpage'} eq '' ||
                   7164: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7165: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7166: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7167: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7168: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7169: 	} 
1.257     albertel 7170: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7171: 	    $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 7172: 	} 
1.257     albertel 7173: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7174: 	    $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 7175: 	} 
                   7176:     } else {
1.596.2.12.2.  1(raebur 7177:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7178:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7179: 	$r->print('
1.596.2.12.2.  (raeburn 7180:): '.$warning.$bubbledbyhand.'
1.492     albertel 7181: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7182: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7183: ');
1.237     albertel 7184:     }
1.596.2.12.2.  1(raebur 7185:0):     $r->print("</form><br />");
1.203     albertel 7186:     return '';
                   7187: }
                   7188: 
1.423     albertel 7189: =pod
                   7190: 
                   7191: =item scantron_form_start
                   7192: 
1.424     albertel 7193:     html hidden input for remembering all selected grading options
                   7194: 
1.423     albertel 7195: =cut
                   7196: 
1.203     albertel 7197: sub scantron_form_start {
                   7198:     my ($max_bubble)=@_;
                   7199:     my $result= <<SCANTRONFORM;
                   7200: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7201:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7202:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7203:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7204:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7205:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7206:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7207:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7208:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7209:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7210: SCANTRONFORM
1.447     foxr     7211: 
                   7212:   my $line = 0;
                   7213:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7214:        my $chunk =
                   7215: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7216:        $chunk .=
                   7217: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7218:        $chunk .= 
                   7219:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7220:        $chunk .=
                   7221:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7222:3):        $chunk .=
                   7223:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7224:        $result .= $chunk;
                   7225:        $line++;
1.596.2.12.2.  6(raebur 7226:3):     }
1.203     albertel 7227:     return $result;
                   7228: }
                   7229: 
1.423     albertel 7230: =pod
                   7231: 
                   7232: =item scantron_validate_file
                   7233: 
1.596.2.6  raeburn  7234:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7235: 
                   7236:     Also processes any necessary information resets that need to
                   7237:     occur before validation begins (ignore previous corrections,
                   7238:     restarting the skipped records processing)
                   7239: 
1.423     albertel 7240: =cut
                   7241: 
1.157     albertel 7242: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7243:0):     my ($r,$symb) = @_;
1.157     albertel 7244:     if (!$symb) {return '';}
1.324     albertel 7245:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7246:     
1.596.2.12.2.  0(raebur 7247:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7248:     # them when doing the corrections reset
1.257     albertel 7249:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7250: 	&reset_skipping_status();
                   7251:     }
1.257     albertel 7252:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7253: 	&remember_current_skipped();
1.257     albertel 7254: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7255:     }
                   7256: 
1.257     albertel 7257:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7258: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7259: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7260: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7261: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7262:     }
1.200     albertel 7263: 
1.257     albertel 7264:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7265: 	&scantron_process_corrections($r);
                   7266:     }
1.503     raeburn  7267:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7268:     #get the student pick code ready
                   7269:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7270:     my $nav_error;
1.596.2.12.2.  9(raebur 7271:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7272:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7273:     if ($nav_error) {
                   7274:         $r->print(&navmap_errormsg());
                   7275:         return '';
                   7276:     }
1.203     albertel 7277:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7278:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7279:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7280:):     }
1.157     albertel 7281:     $r->print($result);
                   7282:     
1.334     albertel 7283:     my @validate_phases=( 'sequence',
                   7284: 			  'ID',
1.157     albertel 7285: 			  'CODE',
                   7286: 			  'doublebubble',
                   7287: 			  'missingbubbles');
1.257     albertel 7288:     if (!$env{'form.validatepass'}) {
                   7289: 	$env{'form.validatepass'} = 0;
1.157     albertel 7290:     }
1.257     albertel 7291:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7292: 
1.448     foxr     7293: 
1.157     albertel 7294:     my $stop=0;
                   7295:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7296: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7297: 	$r->rflush();
1.596.2.12.2.  6(raebur 7298:3): 
1.157     albertel 7299: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7300: 	{
                   7301: 	    no strict 'refs';
                   7302: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7303: 	}
                   7304:     }
                   7305:     if (!$stop) {
1.596.2.12.2.  1(raebur 7306:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7307: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7308:                   $warning.
                   7309:                   &mt('Perform verification for each student after storage of submissions?').
                   7310:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7311:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7312:                   ('&nbsp;'x3).'<label>'.
                   7313:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7314:                   '</label></span><br />'.
                   7315:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7316:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7317:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7318:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7319:     } else {
                   7320: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7321: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7322:     }
                   7323:     if ($stop) {
1.334     albertel 7324: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7325: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7326: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7327: 
1.596.2.12.2.  1(raebur 7328: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 7329: 	} else {
1.503     raeburn  7330:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7331: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7332:             } else {
1.539     riegler  7333:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7334:             }
1.492     albertel 7335: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7336: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7337: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7338: 	}
1.157     albertel 7339:     }
1.596.2.12.2.  1(raebur 7340:0):     $r->print(" </form><br />");
1.157     albertel 7341:     return '';
                   7342: }
                   7343: 
1.423     albertel 7344: 
                   7345: =pod
                   7346: 
                   7347: =item scantron_remove_file
                   7348: 
1.596.2.6  raeburn  7349:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7350:    scantron_original_<filename> is never removed
                   7351: 
                   7352: 
1.423     albertel 7353: =cut
                   7354: 
1.200     albertel 7355: sub scantron_remove_file {
1.192     albertel 7356:     my ($which)=@_;
1.257     albertel 7357:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7358:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7359:     my $file='scantron_';
1.200     albertel 7360:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7361: 	$file.=$which.'_';
1.192     albertel 7362:     } else {
                   7363: 	return 'refused';
                   7364:     }
1.257     albertel 7365:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7366:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7367: }
                   7368: 
1.423     albertel 7369: 
                   7370: =pod
                   7371: 
                   7372: =item scantron_remove_scan_data
                   7373: 
1.596.2.6  raeburn  7374:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7375:    data file.  (In the case that both the are doing skipped records we need
                   7376:    to remember the old skipped lines for the time being so that element
                   7377:    persists for a while.)
                   7378: 
1.423     albertel 7379: =cut
                   7380: 
1.200     albertel 7381: sub scantron_remove_scan_data {
1.257     albertel 7382:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7383:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7384:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7385:     my @todelete;
1.257     albertel 7386:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7387:     foreach my $key (@keys) {
                   7388: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7389: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7390: 		$key=~/remember_skipping/) {
                   7391: 		next;
                   7392: 	    }
1.192     albertel 7393: 	    push(@todelete,$key);
                   7394: 	}
                   7395:     }
1.200     albertel 7396:     my $result;
1.192     albertel 7397:     if (@todelete) {
1.491     albertel 7398: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7399: 				       \@todelete,$cdom,$cname);
                   7400:     } else {
                   7401: 	$result = 'ok';
1.192     albertel 7402:     }
                   7403:     return $result;
                   7404: }
                   7405: 
1.423     albertel 7406: 
                   7407: =pod
                   7408: 
                   7409: =item scantron_getfile
                   7410: 
1.596.2.6  raeburn  7411:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7412:     the scan_data hash
                   7413:   
                   7414:   Arguments:
                   7415:     None
                   7416: 
                   7417:   Returns:
                   7418:     2 hash references
                   7419: 
                   7420:      - first one has 
                   7421:          orig      -
                   7422:          corrected -
                   7423:          skipped   -  each of which points to an array ref of the specified
                   7424:                       file broken up into individual lines
                   7425:          count     - number of scanlines
                   7426:  
                   7427:      - second is the scan_data hash possible keys are
1.425     albertel 7428:        ($number refers to scanline numbered $number and thus the key affects
                   7429:         only that scanline
                   7430:         $bubline refers to the specific bubble line element and the aspects
                   7431:         refers to that specific bubble line element)
                   7432: 
                   7433:        $number.user - username:domain to use
                   7434:        $number.CODE_ignore_dup 
                   7435:                     - ignore the duplicate CODE error 
                   7436:        $number.useCODE
                   7437:                     - use the CODE in the scanline as is
                   7438:        $number.no_bubble.$bubline
                   7439:                     - it is valid that there is no bubbled in bubble
                   7440:                       at $number $bubline
                   7441:        remember_skipping
                   7442:                     - a frozen hash containing keys of $number and values
                   7443:                       of either 
                   7444:                         1 - we are on a 'do skipped records pass' and plan
                   7445:                             on processing this line
                   7446:                         2 - we are on a 'do skipped records pass' and this
                   7447:                             scanline has been marked to skip yet again
1.424     albertel 7448: 
1.423     albertel 7449: =cut
                   7450: 
1.157     albertel 7451: sub scantron_getfile {
1.200     albertel 7452:     #FIXME really would prefer a scantron directory
1.257     albertel 7453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7455:     my $lines;
                   7456:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7457: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7458:     my %scanlines;
                   7459:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7460:     my $temp=$scanlines{'orig'};
                   7461:     $scanlines{'count'}=$#$temp;
                   7462: 
                   7463:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7464: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7465:     if ($lines eq '-1') {
                   7466: 	$scanlines{'corrected'}=[];
                   7467:     } else {
                   7468: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7469:     }
                   7470:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7471: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7472:     if ($lines eq '-1') {
                   7473: 	$scanlines{'skipped'}=[];
                   7474:     } else {
                   7475: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7476:     }
1.175     albertel 7477:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7478:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7479:     my %scan_data = @tmp;
                   7480:     return (\%scanlines,\%scan_data);
                   7481: }
                   7482: 
1.423     albertel 7483: =pod
                   7484: 
                   7485: =item lonnet_putfile
                   7486: 
1.424     albertel 7487:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7488: 
                   7489:  Arguments:
                   7490:    $contents - data to store
                   7491:    $filename - filename to store $contents into
                   7492: 
                   7493:  Returns:
                   7494:    result value from &Apache::lonnet::finishuserfileupload
                   7495: 
1.423     albertel 7496: =cut
                   7497: 
1.157     albertel 7498: sub lonnet_putfile {
                   7499:     my ($contents,$filename)=@_;
1.257     albertel 7500:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7501:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7502:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7503:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7504: 
                   7505: }
                   7506: 
1.423     albertel 7507: =pod
                   7508: 
                   7509: =item scantron_putfile
                   7510: 
1.596.2.6  raeburn  7511:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7512:     scan_data hash. (Does not modify the original version only the
                   7513:     corrected and skipped versions.
                   7514: 
                   7515:  Arguments:
                   7516:     $scanlines - hash ref that looks like the first return value from
                   7517:                  &scantron_getfile()
                   7518:     $scan_data - hash ref that looks like the second return value from
                   7519:                  &scantron_getfile()
                   7520: 
1.423     albertel 7521: =cut
                   7522: 
1.157     albertel 7523: sub scantron_putfile {
                   7524:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7525:     #FIXME really would prefer a scantron directory
1.257     albertel 7526:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7528:     if ($scanlines) {
                   7529: 	my $prefix='scantron_';
1.157     albertel 7530: # no need to update orig, shouldn't change
                   7531: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7532: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7533: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7534: 			$prefix.'corrected_'.
1.257     albertel 7535: 			$env{'form.scantron_selectfile'});
1.200     albertel 7536: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7537: 			$prefix.'skipped_'.
1.257     albertel 7538: 			$env{'form.scantron_selectfile'});
1.200     albertel 7539:     }
1.175     albertel 7540:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7541: }
                   7542: 
1.423     albertel 7543: =pod
                   7544: 
                   7545: =item scantron_get_line
                   7546: 
1.424     albertel 7547:    Returns the correct version of the scanline
                   7548: 
                   7549:  Arguments:
                   7550:     $scanlines - hash ref that looks like the first return value from
                   7551:                  &scantron_getfile()
                   7552:     $scan_data - hash ref that looks like the second return value from
                   7553:                  &scantron_getfile()
                   7554:     $i         - number of the requested line (starts at 0)
                   7555: 
                   7556:  Returns:
                   7557:    A scanline, (either the original or the corrected one if it
                   7558:    exists), or undef if the requested scanline should be
                   7559:    skipped. (Either because it's an skipped scanline, or it's an
                   7560:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7561:    pass.
                   7562: 
1.423     albertel 7563: =cut
                   7564: 
1.157     albertel 7565: sub scantron_get_line {
1.200     albertel 7566:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7567:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7568:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7569:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7570:     return $scanlines->{'orig'}[$i]; 
                   7571: }
                   7572: 
1.423     albertel 7573: =pod
                   7574: 
                   7575: =item scantron_todo_count
                   7576: 
1.424     albertel 7577:     Counts the number of scanlines that need processing.
                   7578: 
                   7579:  Arguments:
                   7580:     $scanlines - hash ref that looks like the first return value from
                   7581:                  &scantron_getfile()
                   7582:     $scan_data - hash ref that looks like the second return value from
                   7583:                  &scantron_getfile()
                   7584: 
                   7585:  Returns:
                   7586:     $count - number of scanlines to process
                   7587: 
1.423     albertel 7588: =cut
                   7589: 
1.200     albertel 7590: sub get_todo_count {
                   7591:     my ($scanlines,$scan_data)=@_;
                   7592:     my $count=0;
                   7593:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7594: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7595: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7596: 	$count++;
                   7597:     }
                   7598:     return $count;
                   7599: }
                   7600: 
1.423     albertel 7601: =pod
                   7602: 
                   7603: =item scantron_put_line
                   7604: 
1.596.2.6  raeburn  7605:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7606:     data file.
                   7607: 
                   7608:  Arguments:
                   7609:     $scanlines - hash ref that looks like the first return value from
                   7610:                  &scantron_getfile()
                   7611:     $scan_data - hash ref that looks like the second return value from
                   7612:                  &scantron_getfile()
                   7613:     $i         - line number to update
                   7614:     $newline   - contents of the updated scanline
                   7615:     $skip      - if true make the line for skipping and update the
                   7616:                  'skipped' file
                   7617: 
1.423     albertel 7618: =cut
                   7619: 
1.157     albertel 7620: sub scantron_put_line {
1.200     albertel 7621:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7622:     if ($skip) {
                   7623: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7624: 	&start_skipping($scan_data,$i);
1.157     albertel 7625: 	return;
                   7626:     }
                   7627:     $scanlines->{'corrected'}[$i]=$newline;
                   7628: }
                   7629: 
1.423     albertel 7630: =pod
                   7631: 
                   7632: =item scantron_clear_skip
                   7633: 
1.424     albertel 7634:    Remove a line from the 'skipped' file
                   7635: 
                   7636:  Arguments:
                   7637:     $scanlines - hash ref that looks like the first return value from
                   7638:                  &scantron_getfile()
                   7639:     $scan_data - hash ref that looks like the second return value from
                   7640:                  &scantron_getfile()
                   7641:     $i         - line number to update
                   7642: 
1.423     albertel 7643: =cut
                   7644: 
1.376     albertel 7645: sub scantron_clear_skip {
                   7646:     my ($scanlines,$scan_data,$i)=@_;
                   7647:     if (exists($scanlines->{'skipped'}[$i])) {
                   7648: 	undef($scanlines->{'skipped'}[$i]);
                   7649: 	return 1;
                   7650:     }
                   7651:     return 0;
                   7652: }
                   7653: 
1.423     albertel 7654: =pod
                   7655: 
                   7656: =item scantron_filter_not_exam
                   7657: 
1.424     albertel 7658:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7659:    filter out resources that are not marked as 'exam' mode
                   7660: 
1.423     albertel 7661: =cut
                   7662: 
1.334     albertel 7663: sub scantron_filter_not_exam {
                   7664:     my ($curres)=@_;
                   7665:     
                   7666:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7667: 	# if the user has asked to not have either hidden
                   7668: 	# or 'randomout' controlled resources to be graded
                   7669: 	# don't include them
                   7670: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7671: 	    && $curres->randomout) {
                   7672: 	    return 0;
                   7673: 	}
                   7674: 	return 1;
                   7675:     }
                   7676:     return 0;
                   7677: }
                   7678: 
1.423     albertel 7679: =pod
                   7680: 
                   7681: =item scantron_validate_sequence
                   7682: 
1.424     albertel 7683:     Validates the selected sequence, checking for resource that are
                   7684:     not set to exam mode.
                   7685: 
1.423     albertel 7686: =cut
                   7687: 
1.334     albertel 7688: sub scantron_validate_sequence {
                   7689:     my ($r,$currentphase) = @_;
                   7690: 
                   7691:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7692:     unless (ref($navmap)) {
                   7693:         $r->print(&navmap_errormsg());
                   7694:         return (1,$currentphase);
                   7695:     }
1.334     albertel 7696:     my (undef,undef,$sequence)=
                   7697: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7698: 
                   7699:     my $map=$navmap->getResourceByUrl($sequence);
                   7700: 
                   7701:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7702:                                     value="ignore" />');
                   7703:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7704: 	my @resources=
                   7705: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7706: 	if (@resources) {
1.596.2.12.2.  0(raebur 7707:2): 	    $r->print('<p class="LC_warning">'
                   7708:2):                .&mt('Some resources in the sequence currently are not set to'
                   7709:2):                    .' exam mode. Grading these resources currently may not'
                   7710:2):                    .' work correctly.')
                   7711:2):                .'</p>'
                   7712:2):             );
1.334     albertel 7713: 	    return (1,$currentphase);
                   7714: 	}
                   7715:     }
                   7716: 
                   7717:     return (0,$currentphase+1);
                   7718: }
                   7719: 
1.423     albertel 7720: 
                   7721: 
1.157     albertel 7722: sub scantron_validate_ID {
                   7723:     my ($r,$currentphase) = @_;
                   7724:     
                   7725:     #get student info
                   7726:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7727:     my %idmap=&username_to_idmap($classlist);
                   7728: 
                   7729:     #get scantron line setup
1.596.2.12.2.  9(raebur 7730:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7731:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7732: 
                   7733:     my $nav_error;
1.596.2.12.2.  (raeburn 7734:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7735:     if ($nav_error) {
                   7736:         $r->print(&navmap_errormsg());
                   7737:         return(1,$currentphase);
                   7738:     }
1.157     albertel 7739: 
                   7740:     my %found=('ids'=>{},'usernames'=>{});
                   7741:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7742: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7743: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7744: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7745: 						 $scan_data);
                   7746: 	my $id=$$scan_record{'scantron.ID'};
                   7747: 	my $found;
                   7748: 	foreach my $checkid (keys(%idmap)) {
                   7749: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7750: 	}
                   7751: 	if ($found) {
                   7752: 	    my $username=$idmap{$found};
                   7753: 	    if ($found{'ids'}{$found}) {
                   7754: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7755: 					 $line,'duplicateID',$found);
1.194     albertel 7756: 		return(1,$currentphase);
1.157     albertel 7757: 	    } elsif ($found{'usernames'}{$username}) {
                   7758: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7759: 					 $line,'duplicateID',$username);
1.194     albertel 7760: 		return(1,$currentphase);
1.157     albertel 7761: 	    }
1.186     albertel 7762: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7763: 	    $found{'ids'}{$found}++;
                   7764: 	    $found{'usernames'}{$username}++;
                   7765: 	} else {
                   7766: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7767: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7768: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7769: 		    &scantron_get_correction($r,$i,$scan_record,
                   7770: 					     \%scantron_config,
                   7771: 					     $line,'duplicateID',$username);
1.194     albertel 7772: 		    return(1,$currentphase);
1.157     albertel 7773: 		} elsif (!defined($username)) {
                   7774: 		    &scantron_get_correction($r,$i,$scan_record,
                   7775: 					     \%scantron_config,
                   7776: 					     $line,'incorrectID');
1.194     albertel 7777: 		    return(1,$currentphase);
1.157     albertel 7778: 		}
                   7779: 		$found{'usernames'}{$username}++;
                   7780: 	    } else {
                   7781: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7782: 					 $line,'incorrectID');
1.194     albertel 7783: 		return(1,$currentphase);
1.157     albertel 7784: 	    }
                   7785: 	}
                   7786:     }
                   7787: 
                   7788:     return (0,$currentphase+1);
                   7789: }
                   7790: 
1.423     albertel 7791: 
1.157     albertel 7792: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7793:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7794:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7795: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7796: #to show both the current line and the previous one and allow skipping
                   7797: #the previous one or the current one
                   7798: 
1.333     albertel 7799:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7800:         $r->print(
                   7801:             '<p class="LC_warning">'
                   7802:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7803:                 "<b>$error</b>",
                   7804:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7805:            ."</p> \n");
1.157     albertel 7806:     } else {
1.596.2.6  raeburn  7807:         $r->print(
                   7808:             '<p class="LC_warning">'
                   7809:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7810:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7811:            ."</p> \n");
                   7812:     }
                   7813:     my $message =
                   7814:         '<p>'
                   7815:        .&mt('The ID on the form is [_1]',
                   7816:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7817:        .'<br />'
1.596.2.12  raeburn  7818:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7819:             $$scan_record{'scantron.LastName'},
                   7820:             $$scan_record{'scantron.FirstName'})
                   7821:        .'</p>';
1.242     albertel 7822: 
1.157     albertel 7823:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7824:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7825:                            # Array populated for doublebubble or
                   7826:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7827:                            # to validate radio button checking   
                   7828: 
1.157     albertel 7829:     if ($error =~ /ID$/) {
1.186     albertel 7830: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7831: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7832: 		      "</p>\n");
1.157     albertel 7833: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7834: 	    $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 7835: 	}
1.242     albertel 7836: 	$r->print($message);
1.492     albertel 7837: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7838: 	$r->print("\n<ul><li> ");
                   7839: 	#FIXME it would be nice if this sent back the user ID and
                   7840: 	#could do partial userID matches
                   7841: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7842: 				       'scantron_username','scantron_domain'));
                   7843: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7844:3): 	$r->print("\n:\n".
1.257     albertel 7845: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7846: 
                   7847: 	$r->print('</li>');
1.186     albertel 7848:     } elsif ($error =~ /CODE$/) {
                   7849: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7850: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7851: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7852: 	    $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 7853: 	}
1.596.2.6  raeburn  7854:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7855:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7856:                  ."</p>\n");
1.242     albertel 7857: 	$r->print($message);
1.596.2.6  raeburn  7858: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7859: 	$r->print("\n<br /> ");
1.194     albertel 7860: 	my $i=0;
1.273     albertel 7861: 	if ($error eq 'incorrectCODE' 
                   7862: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7863: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7864: 	    if ($closest > 0) {
                   7865: 		foreach my $testcode (@{$closest}) {
                   7866: 		    my $checked='';
1.569     bisitz   7867: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7868: 		    $r->print("
                   7869:    <label>
1.569     bisitz   7870:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7871:        ".&mt("Use the similar CODE [_1] instead.",
                   7872: 	    "<b><tt>".$testcode."</tt></b>")."
                   7873:     </label>
                   7874:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7875: 		    $r->print("\n<br />");
                   7876: 		    $i++;
                   7877: 		}
1.194     albertel 7878: 	    }
                   7879: 	}
1.273     albertel 7880: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7881: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7882: 	    $r->print("
                   7883:     <label>
1.569     bisitz   7884:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7885:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7886: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7887:     </label>");
1.273     albertel 7888: 	    $r->print("\n<br />");
                   7889: 	}
1.194     albertel 7890: 
1.596.2.12.2.  1(raebur 7891:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7892: function change_radio(field) {
1.190     albertel 7893:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7894:     var i;
                   7895:     for (i=0;i<slct.length;i++) {
                   7896:         if (slct[i].value==field) { slct[i].checked=true; }
                   7897:     }
                   7898: }
                   7899: ENDSCRIPT
1.187     albertel 7900: 	my $href="/adm/pickcode?".
1.359     www      7901: 	   "form=".&escape("scantronupload").
                   7902: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7903: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7904: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7905: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7906: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7907: 	    $r->print("
                   7908:     <label>
                   7909:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7910:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7911: 	     "<a target='_blank' href='$href'>","</a>")."
                   7912:     </label> 
1.558     bisitz   7913:     ".&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 7914: 	    $r->print("\n<br />");
                   7915: 	}
1.492     albertel 7916: 	$r->print("
                   7917:     <label>
                   7918:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7919:        ".&mt("Use [_1] as the CODE.",
                   7920: 	     "</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 7921: 	$r->print("\n<br /><br />");
1.157     albertel 7922:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7923: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7924: 
                   7925: 	# The form field scantron_questions is acutally a list of line numbers.
                   7926: 	# represented by this form so:
                   7927: 
1.596.2.12.2.  6(raebur 7928:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7929:3):                                                 $respnumlookup,$startline);
1.497     foxr     7930: 
1.157     albertel 7931: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7932: 		  $line_list.'" />');
1.242     albertel 7933: 	$r->print($message);
1.492     albertel 7934: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7935: 	foreach my $question (@{$arg}) {
1.503     raeburn  7936: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7937:3):                                                    $scan_record, $error,
                   7938:3):                                                    $randomorder,$randompick,
                   7939:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7940:             push(@lines_to_correct,@linenums);
1.157     albertel 7941: 	}
1.503     raeburn  7942:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7943:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7944: 	$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 7945: 	$r->print($message);
1.492     albertel 7946: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7947: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7948: 
1.503     raeburn  7949: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7950: 	# a list of question numbers. Therefore:
                   7951: 	#
                   7952: 	
1.596.2.12.2.  6(raebur 7953:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7954:3):                                                 $respnumlookup,$startline);
1.497     foxr     7955: 
1.157     albertel 7956: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7957: 		  $line_list.'" />');
1.157     albertel 7958: 	foreach my $question (@{$arg}) {
1.503     raeburn  7959: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7960:3):                                                    $scan_record, $error,
                   7961:3):                                                    $randomorder,$randompick,
                   7962:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7963:             push(@lines_to_correct,@linenums);
1.157     albertel 7964: 	}
1.503     raeburn  7965:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7966:     } else {
                   7967: 	$r->print("\n<ul>");
                   7968:     }
                   7969:     $r->print("\n</li></ul>");
1.497     foxr     7970: }
                   7971: 
1.503     raeburn  7972: sub verify_bubbles_checked {
                   7973:     my (@ansnums) = @_;
                   7974:     my $ansnumstr = join('","',@ansnums);
                   7975:     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 7976:6):     &js_escape(\$warning);
          1(raebur 7977:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  7978: function verify_bubble_radio(form) {
                   7979:     var ansnumArray = new Array ("$ansnumstr");
                   7980:     var need_bubble_count = 0;
                   7981:     for (var i=0; i<ansnumArray.length; i++) {
                   7982:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7983:             var bubble_picked = 0; 
                   7984:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7985:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7986:                     bubble_picked = 1;
                   7987:                 }
                   7988:             }
                   7989:             if (bubble_picked == 0) {
                   7990:                 need_bubble_count ++;
                   7991:             }
                   7992:         }
                   7993:     }
                   7994:     if (need_bubble_count) {
                   7995:         alert("$warning");
                   7996:         return;
                   7997:     }
                   7998:     form.submit(); 
                   7999: }
                   8000: ENDSCRIPT
                   8001:     return $output;
                   8002: }
                   8003: 
1.497     foxr     8004: =pod
                   8005: 
                   8006: =item  questions_to_line_list
1.157     albertel 8007: 
1.497     foxr     8008: Converts a list of questions into a string of comma separated
                   8009: line numbers in the answer sheet used by the questions.  This is
                   8010: used to fill in the scantron_questions form field.
                   8011: 
                   8012:   Arguments:
                   8013:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8014:3):      randomorder  - True if randomorder in use.
                   8015:3):      randompick   - True if randompick in use.
                   8016:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8017:3):                      for current line to question number used for same question
                   8018:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8019:3):      startline    - Reference to hash where key is question number (0 is first)
                   8020:3):                     and key is number of first bubble line for current student
                   8021:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8022: 
                   8023: =cut
                   8024: 
                   8025: 
                   8026: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8027:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8028:     my @lines;
                   8029: 
1.503     raeburn  8030:     foreach my $item (@{$questions}) {
                   8031:         my $question = $item;
                   8032:         my ($first,$count,$last);
                   8033:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8034:             $question = $1;
                   8035:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8036:3):             my $responsenum = $question-1;
                   8037:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8038:3):                 $responsenum = $respnumlookup->{$question-1};
                   8039:3):                 if (ref($startline) eq 'HASH') {
                   8040:3):                     $first = $startline->{$question-1} + 1;
                   8041:3):                 }
                   8042:3):             } else {
                   8043:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8044:3):             }
          7(raebur 8045:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8046:             my $subcount = 1;
                   8047:             while ($subcount<$subquestion) {
                   8048:                 $first += $subans[$subcount-1];
                   8049:                 $subcount ++;
                   8050:             }
                   8051:             $count = $subans[$subquestion-1];
                   8052:         } else {
1.596.2.12.2.  7(raebur 8053:3):             my $responsenum = $question-1;
                   8054:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8055:3):                 $responsenum = $respnumlookup->{$question-1};
                   8056:3):                 if (ref($startline) eq 'HASH') {
                   8057:3):                     $first = $startline->{$question-1} + 1;
                   8058:3):                 }
                   8059:3):             } else {
                   8060:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8061:3):             }
                   8062:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8063:         }
1.506     raeburn  8064:         $last = $first+$count-1;
1.503     raeburn  8065:         push(@lines, ($first..$last));
1.497     foxr     8066:     }
                   8067:     return join(',', @lines);
                   8068: }
                   8069: 
                   8070: =pod 
                   8071: 
                   8072: =item prompt_for_corrections
                   8073: 
                   8074: Prompts for a potentially multiline correction to the
                   8075: user's bubbling (factors out common code from scantron_get_correction
                   8076: for multi and missing bubble cases).
                   8077: 
                   8078:  Arguments:
                   8079:    $r           - Apache request object.
                   8080:    $question    - The question number to prompt for.
                   8081:    $scan_config - The scantron file configuration hash.
                   8082:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8083:    $error       - Type of error
1.596.2.12.2.  7(raebur 8084:3):    $randomorder - True if randomorder in use.
                   8085:3):    $randompick  - True if randompick in use.
                   8086:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8087:3):                     for current line to question number used for same question
                   8088:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8089:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8090:3):                   and value is number of first bubble line for current student
                   8091:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8092: 
                   8093:  Implicit inputs:
                   8094:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8095:                                   Numbered from 0 (but question numbers are from
                   8096:                                   1.
                   8097:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8098:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8099:                                   type problems render as separate sub-questions, 
1.503     raeburn  8100:                                   in exam mode. This hash contains a 
                   8101:                                   comma-separated list of the lines per 
                   8102:                                   sub-question.
1.510     raeburn  8103:    %responsetype_per_response   - essayresponse, formularesponse,
                   8104:                                   stringresponse, imageresponse, reactionresponse,
                   8105:                                   and organicresponse type problem parts can have
1.503     raeburn  8106:                                   multiple lines per response if the weight
                   8107:                                   assigned exceeds 10.  In this case, only
                   8108:                                   one bubble per line is permitted, but more 
                   8109:                                   than one line might contain bubbles, e.g.
                   8110:                                   bubbling of: line 1 - J, line 2 - J, 
                   8111:                                   line 3 - B would assign 22 points.  
1.497     foxr     8112: 
                   8113: =cut
                   8114: 
                   8115: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8116:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8117:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8118:     my ($current_line,$lines);
                   8119:     my @linenums;
                   8120:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8121:3):     my ($first,$responsenum);
1.503     raeburn  8122:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8123:         $question = $1;
                   8124:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8125:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8126:3):             $responsenum = $respnumlookup->{$question-1};
                   8127:3):             if (ref($startline) eq 'HASH') {
                   8128:3):                 $first = $startline->{$question-1};
                   8129:3):             }
                   8130:3):         } else {
                   8131:3):             $responsenum = $question-1;
          7(raebur 8132:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8133:3):         }
                   8134:3):         $current_line = $first + 1 ;
                   8135:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8136:         my $subcount = 1;
                   8137:         while ($subcount<$subquestion) {
                   8138:             $current_line += $subans[$subcount-1];
                   8139:             $subcount ++;
                   8140:         }
                   8141:         $lines = $subans[$subquestion-1];
                   8142:     } else {
1.596.2.12.2.  6(raebur 8143:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8144:3):             $responsenum = $respnumlookup->{$question-1};
                   8145:3):             if (ref($startline) eq 'HASH') {
                   8146:3):                 $first = $startline->{$question-1};
                   8147:3):             }
                   8148:3):         } else {
                   8149:3):             $responsenum = $question-1;
                   8150:3):             $first = $first_bubble_line{$responsenum};
                   8151:3):         }
                   8152:3):         $current_line = $first + 1;
                   8153:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8154:     }
1.497     foxr     8155:     if ($lines > 1) {
1.503     raeburn  8156:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8157:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8158:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8159:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8160:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8161:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8162:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8163: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  8164:         } else {
                   8165:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8166:         }
1.497     foxr     8167:     }
                   8168:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8169:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8170:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8171: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8172:         push(@linenums,$current_line);
1.497     foxr     8173: 	$current_line++;
                   8174:     }
                   8175:     if ($lines > 1) {
                   8176: 	$r->print("<hr /><br />");
                   8177:     }
1.503     raeburn  8178:     return @linenums;
1.157     albertel 8179: }
1.423     albertel 8180: 
                   8181: =pod
                   8182: 
                   8183: =item scantron_bubble_selector
                   8184:   
                   8185:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8186:    possibly showing the existing the selected bubbles if known
1.423     albertel 8187: 
                   8188:  Arguments:
                   8189:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8190:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8191:     $line        - Number of the line being displayed.
1.503     raeburn  8192:     $questionnum - Question number (may include subquestion)
                   8193:     $error       - Type of error.
1.497     foxr     8194:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8195: 
                   8196: =cut
                   8197: 
1.157     albertel 8198: sub scantron_bubble_selector {
1.503     raeburn  8199:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8200:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8201: 
                   8202:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8203:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8204:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8205:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8206:):             $max=$$scan_config{'BubblesPerRow'};
                   8207:):             if (($scmode eq 'number') && ($max > 10)) {
                   8208:):                 $max = 10;
                   8209:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8210:):                 $max = 26;
                   8211:):             }
                   8212:):         } else {
                   8213:):             $max = 10;
                   8214:):         }
                   8215:):     }
1.274     albertel 8216: 
1.157     albertel 8217:     my @alphabet=('A'..'Z');
1.503     raeburn  8218:     $r->print(&Apache::loncommon::start_data_table().
                   8219:               &Apache::loncommon::start_data_table_row());
                   8220:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8221:     for (my $i=0;$i<$max+1;$i++) {
                   8222: 	$r->print("\n".'<td align="center">');
                   8223: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8224: 	else { $r->print('&nbsp;'); }
                   8225: 	$r->print('</td>');
                   8226:     }
1.503     raeburn  8227:     $r->print(&Apache::loncommon::end_data_table_row().
                   8228:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8229:     for (my $i=0;$i<$max;$i++) {
                   8230: 	$r->print("\n".
                   8231: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8232: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8233:     }
1.503     raeburn  8234:     my $nobub_checked = ' ';
                   8235:     if ($error eq 'missingbubble') {
                   8236:         $nobub_checked = ' checked = "checked" ';
                   8237:     }
                   8238:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8239: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8240:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8241:               $line.'" value="'.$questionnum.'" /></td>');
                   8242:     $r->print(&Apache::loncommon::end_data_table_row().
                   8243:               &Apache::loncommon::end_data_table());
1.157     albertel 8244: }
                   8245: 
1.423     albertel 8246: =pod
                   8247: 
                   8248: =item num_matches
                   8249: 
1.424     albertel 8250:    Counts the number of characters that are the same between the two arguments.
                   8251: 
                   8252:  Arguments:
                   8253:    $orig - CODE from the scanline
                   8254:    $code - CODE to match against
                   8255: 
                   8256:  Returns:
                   8257:    $count - integer count of the number of same characters between the
                   8258:             two arguments
                   8259: 
1.423     albertel 8260: =cut
                   8261: 
1.194     albertel 8262: sub num_matches {
                   8263:     my ($orig,$code) = @_;
                   8264:     my @code=split(//,$code);
                   8265:     my @orig=split(//,$orig);
                   8266:     my $same=0;
                   8267:     for (my $i=0;$i<scalar(@code);$i++) {
                   8268: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8269:     }
                   8270:     return $same;
                   8271: }
                   8272: 
1.423     albertel 8273: =pod
                   8274: 
                   8275: =item scantron_get_closely_matching_CODEs
                   8276: 
1.424     albertel 8277:    Cycles through all CODEs and finds the set that has the greatest
                   8278:    number of same characters as the provided CODE
                   8279: 
                   8280:  Arguments:
                   8281:    $allcodes - hash ref returned by &get_codes()
                   8282:    $CODE     - CODE from the current scanline
                   8283: 
                   8284:  Returns:
                   8285:    2 element list
                   8286:     - first elements is number of how closely matching the best fit is 
                   8287:       (5 means best set has 5 matching characters)
                   8288:     - second element is an arrary ref containing the set of valid CODEs
                   8289:       that best fit the passed in CODE
                   8290: 
1.423     albertel 8291: =cut
                   8292: 
1.194     albertel 8293: sub scantron_get_closely_matching_CODEs {
                   8294:     my ($allcodes,$CODE)=@_;
                   8295:     my @CODEs;
                   8296:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8297: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8298:     }
                   8299: 
                   8300:     return ($#CODEs,$CODEs[-1]);
                   8301: }
                   8302: 
1.423     albertel 8303: =pod
                   8304: 
                   8305: =item get_codes
                   8306: 
1.424     albertel 8307:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8308:    set of remembered CODEs.
                   8309: 
                   8310:  Arguments:
                   8311:   $old_name - name of the set of remembered CODEs
                   8312:   $cdom     - domain of the course
                   8313:   $cnum     - internal course name
                   8314: 
                   8315:  Returns:
                   8316:   %allcodes - keys are the valid CODEs, values are all 1
                   8317: 
1.423     albertel 8318: =cut
                   8319: 
1.194     albertel 8320: sub get_codes {
1.280     foxr     8321:     my ($old_name, $cdom, $cnum) = @_;
                   8322:     if (!$old_name) {
                   8323: 	$old_name=$env{'form.scantron_CODElist'};
                   8324:     }
                   8325:     if (!$cdom) {
                   8326: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8327:     }
                   8328:     if (!$cnum) {
                   8329: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8330:     }
1.278     albertel 8331:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8332: 				    $cdom,$cnum);
                   8333:     my %allcodes;
                   8334:     if ($result{"type\0$old_name"} eq 'number') {
                   8335: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8336:     } else {
                   8337: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8338:     }
1.194     albertel 8339:     return %allcodes;
                   8340: }
                   8341: 
1.423     albertel 8342: =pod
                   8343: 
                   8344: =item scantron_validate_CODE
                   8345: 
1.424     albertel 8346:    Validates all scanlines in the selected file to not have any
                   8347:    invalid or underspecified CODEs and that none of the codes are
                   8348:    duplicated if this was requested.
                   8349: 
1.423     albertel 8350: =cut
                   8351: 
1.157     albertel 8352: sub scantron_validate_CODE {
                   8353:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8354:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8355:     if ($scantron_config{'CODElocation'} &&
                   8356: 	$scantron_config{'CODEstart'} &&
                   8357: 	$scantron_config{'CODElength'}) {
1.257     albertel 8358: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8359: 	    &FIXME_blow_up()
                   8360: 	}
                   8361:     } else {
                   8362: 	return (0,$currentphase+1);
                   8363:     }
                   8364:     
                   8365:     my %usedCODEs;
                   8366: 
1.194     albertel 8367:     my %allcodes=&get_codes();
1.186     albertel 8368: 
1.582     raeburn  8369:     my $nav_error;
1.596.2.12.2.  (raeburn 8370:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8371:     if ($nav_error) {
                   8372:         $r->print(&navmap_errormsg());
                   8373:         return(1,$currentphase);
                   8374:     }
1.447     foxr     8375: 
1.186     albertel 8376:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8377:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8378: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8379: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8380: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8381: 						 $scan_data);
                   8382: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8383: 	my $error=0;
1.224     albertel 8384: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8385: 	    &scantron_get_correction($r,$i,$scan_record,
                   8386: 				     \%scantron_config,
                   8387: 				     $line,'incorrectCODE',\%allcodes);
                   8388: 	    return(1,$currentphase);
                   8389: 	}
1.221     albertel 8390: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8391: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8392: 	    &scantron_get_correction($r,$i,$scan_record,
                   8393: 				     \%scantron_config,
1.194     albertel 8394: 				     $line,'incorrectCODE',\%allcodes);
                   8395: 	    return(1,$currentphase);
1.186     albertel 8396: 	}
1.214     albertel 8397: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8398: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8399: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8400: 	    &scantron_get_correction($r,$i,$scan_record,
                   8401: 				     \%scantron_config,
1.194     albertel 8402: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8403: 	    return(1,$currentphase);
1.186     albertel 8404: 	}
1.524     raeburn  8405: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8406:     }
1.157     albertel 8407:     return (0,$currentphase+1);
                   8408: }
                   8409: 
1.423     albertel 8410: =pod
                   8411: 
                   8412: =item scantron_validate_doublebubble
                   8413: 
1.424     albertel 8414:    Validates all scanlines in the selected file to not have any
                   8415:    bubble lines with multiple bubbles marked.
                   8416: 
1.423     albertel 8417: =cut
                   8418: 
1.157     albertel 8419: sub scantron_validate_doublebubble {
                   8420:     my ($r,$currentphase) = @_;
                   8421:     #get student info
                   8422:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8423:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8424:3):     my (undef,undef,$sequence)=
                   8425:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8426: 
                   8427:     #get scantron line setup
1.596.2.12.2.  9(raebur 8428:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8429:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8430:3): 
                   8431:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8432:3):     unless (ref($navmap)) {
                   8433:3):         $r->print(&navmap_errormsg());
                   8434:3):         return(1,$currentphase);
                   8435:3):     }
                   8436:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8437:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8438:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8439:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8440:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8441:3): 
1.583     raeburn  8442:     my $nav_error;
1.596.2.12.2.  6(raebur 8443:3):     if (ref($map)) {
                   8444:3):         $randomorder = $map->randomorder();
                   8445:3):         $randompick = $map->randompick();
                   8446:3):         if ($randomorder || $randompick) {
                   8447:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8448:3):             if ($nav_error) {
                   8449:3):                 $r->print(&navmap_errormsg());
                   8450:3):                 return(1,$currentphase);
                   8451:3):             }
                   8452:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8453:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8454:3):         }
                   8455:3):     } else {
                   8456:3):         $r->print(&navmap_errormsg());
                   8457:3):         return(1,$currentphase);
                   8458:3):     }
                   8459:3): 
          (raeburn 8460:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8461:     if ($nav_error) {
                   8462:         $r->print(&navmap_errormsg());
                   8463:         return(1,$currentphase);
                   8464:     }
1.447     foxr     8465: 
1.157     albertel 8466:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8467: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8468: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8469: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8470:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8471:3):                                                  $randompick,$sequence,\@master_seq,
                   8472:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8473:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8474: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8475: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8476: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8477:3): 				 $$scan_record{'scantron.doubleerror'},
                   8478:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8479:     	return (1,$currentphase);
                   8480:     }
                   8481:     return (0,$currentphase+1);
                   8482: }
                   8483: 
1.423     albertel 8484: 
1.503     raeburn  8485: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8486:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8487:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8488: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8489: 	&restore_bubble_lines();
1.257     albertel 8490: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8491:     }
1.330     albertel 8492: 
1.447     foxr     8493:     my (undef, undef, $sequence) =
1.257     albertel 8494: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8495: 
1.447     foxr     8496:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8497:     unless (ref($navmap)) {
                   8498:         if (ref($nav_error)) {
                   8499:             $$nav_error = 1;
                   8500:         }
1.591     raeburn  8501:         return;
1.582     raeburn  8502:     }
1.191     albertel 8503:     my $map=$navmap->getResourceByUrl($sequence);
                   8504:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8505:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8506: 
                   8507:     &Apache::lonxml::clear_problem_counter();
                   8508: 
1.557     raeburn  8509:     my $uname       = $env{'user.name'};
                   8510:     my $udom        = $env{'user.domain'};
1.435     foxr     8511:     my $cid         = $env{'request.course.id'};
                   8512:     my $total_lines = 0;
                   8513:     %bubble_lines_per_response = ();
1.447     foxr     8514:     %first_bubble_line         = ();
1.503     raeburn  8515:     %subdivided_bubble_lines   = ();
                   8516:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8517:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8518: 
1.447     foxr     8519:     my $response_number = 0;
                   8520:     my $bubble_line     = 0;
1.191     albertel 8521:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8522:3):         my $resid = $resource->id();
          (raeburn 8523:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8524:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8525:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8526: 	    foreach my $part_id (@{$parts}) {
                   8527:                 my $lines;
                   8528: 
                   8529: 	        # TODO - make this a persistent hash not an array.
                   8530: 
                   8531:                 # optionresponse, matchresponse and rankresponse type items 
                   8532:                 # render as separate sub-questions in exam mode.
                   8533:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8534:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8535:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8536:                     my ($numbub,$numshown);
                   8537:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8538:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8539:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8540:                         }
                   8541:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8542:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8543:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8544:                         }
                   8545:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8546:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8547:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8548:                         }
                   8549:                     }
                   8550:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8551:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8552:                     }
1.596.2.12.2.  (raeburn 8553:):                     my $bubbles_per_row =
                   8554:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8555:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8556:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8557:                         $inner_bubble_lines++;
                   8558:                     }
                   8559:                     for (my $i=0; $i<$numshown; $i++) {
                   8560:                         $subdivided_bubble_lines{$response_number} .= 
                   8561:                             $inner_bubble_lines.',';
                   8562:                     }
                   8563:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8564:                     $lines = $numshown * $inner_bubble_lines;
                   8565:                 } else {
                   8566:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8567:):                 }
1.542     raeburn  8568: 
                   8569:                 $first_bubble_line{$response_number} = $bubble_line;
                   8570: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8571:                 $responsetype_per_response{$response_number} = 
                   8572:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8573:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8574: 	        $response_number++;
                   8575: 
                   8576: 	        $bubble_line +=  $lines;
                   8577: 	        $total_lines +=  $lines;
                   8578: 	    }
                   8579:         }
                   8580:     }
1.552     raeburn  8581:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8582: 
                   8583:     &save_bubble_lines();
                   8584:     $env{'form.scantron_maxbubble'} =
                   8585: 	$total_lines;
                   8586:     return $env{'form.scantron_maxbubble'};
                   8587: }
1.523     raeburn  8588: 
1.596.2.12.2.  (raeburn 8589:): sub bubblesheet_bubbles_per_row {
                   8590:):     my ($scantron_config) = @_;
                   8591:):     my $bubbles_per_row;
                   8592:):     if (ref($scantron_config) eq 'HASH') {
                   8593:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8594:):     }
                   8595:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8596:):         $bubbles_per_row = 10;
                   8597:):     }
                   8598:):     return $bubbles_per_row;
                   8599:): }
                   8600:): 
1.157     albertel 8601: sub scantron_validate_missingbubbles {
                   8602:     my ($r,$currentphase) = @_;
                   8603:     #get student info
                   8604:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8605:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8606:3):     my (undef,undef,$sequence)=
                   8607:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8608: 
                   8609:     #get scantron line setup
1.596.2.12.2.  9(raebur 8610:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8611:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8612:3): 
                   8613:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8614:3):     unless (ref($navmap)) {
                   8615:3):         $r->print(&navmap_errormsg());
                   8616:3):         return(1,$currentphase);
                   8617:3):     }
                   8618:3): 
                   8619:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8620:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8621:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8622:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8623:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8624:3): 
1.582     raeburn  8625:     my $nav_error;
1.596.2.12.2.  6(raebur 8626:3):     if (ref($map)) {
                   8627:3):         $randomorder = $map->randomorder();
                   8628:3):         $randompick = $map->randompick();
          7(raebur 8629:3):         if ($randomorder || $randompick) {
                   8630:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8631:3):             if ($nav_error) {
                   8632:3):                 $r->print(&navmap_errormsg());
                   8633:3):                 return(1,$currentphase);
                   8634:3):             }
                   8635:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8636:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8637:3):         }
          6(raebur 8638:3):     } else {
                   8639:3):         $r->print(&navmap_errormsg());
          7(raebur 8640:3):         return(1,$currentphase);
          6(raebur 8641:3):     }
                   8642:3): 
                   8643:3): 
          (raeburn 8644:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8645:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8646:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8647:         return(1,$currentphase);
                   8648:     }
1.596.2.12.2.  6(raebur 8649:3): 
1.157     albertel 8650:     if (!$max_bubble) { $max_bubble=2**31; }
                   8651:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8652: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8653: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8654:3):         my $scan_record =
                   8655:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8656:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8657:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8658:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8659: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8660: 	my @to_correct;
1.470     foxr     8661: 	
                   8662: 	# Probably here's where the error is...
                   8663: 
1.157     albertel 8664: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8665:             my $lastbubble;
                   8666:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8667:3):                 my $question = $1;
                   8668:3):                 my $subquestion = $2;
                   8669:3):                 my ($first,$responsenum);
                   8670:3):                 if ($randomorder || $randompick) {
                   8671:3):                     $responsenum = $respnumlookup{$question-1};
                   8672:3):                     $first = $startline{$question-1};
                   8673:3):                 } else {
                   8674:3):                     $responsenum = $question-1;
                   8675:3):                     $first = $first_bubble_line{$responsenum};
                   8676:3):                 }
                   8677:3):                 if (!defined($first)) { next; }
          7(raebur 8678:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8679:3):                 my $subcount = 1;
                   8680:3):                 while ($subcount<$subquestion) {
                   8681:3):                     $first += $subans[$subcount-1];
                   8682:3):                     $subcount ++;
                   8683:3):                 }
                   8684:3):                 my $count = $subans[$subquestion-1];
                   8685:3):                 $lastbubble = $first + $count;
1.505     raeburn  8686:             } else {
1.596.2.12.2.  6(raebur 8687:3):                 my ($first,$responsenum);
                   8688:3):                 if ($randomorder || $randompick) {
                   8689:3):                     $responsenum = $respnumlookup{$missing-1};
                   8690:3):                     $first = $startline{$missing-1};
                   8691:3):                 } else {
                   8692:3):                     $responsenum = $missing-1;
                   8693:3):                     $first = $first_bubble_line{$responsenum};
                   8694:3):                 }
                   8695:3):                 if (!defined($first)) { next; }
                   8696:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8697:             }
                   8698:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8699: 	    push(@to_correct,$missing);
                   8700: 	}
                   8701: 	if (@to_correct) {
                   8702: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8703:3): 				     $line,'missingbubble',\@to_correct,
                   8704:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8705:3):                                      \%startline);
1.157     albertel 8706: 	    return (1,$currentphase);
                   8707: 	}
                   8708: 
                   8709:     }
                   8710:     return (0,$currentphase+1);
                   8711: }
                   8712: 
1.596.2.12.2.  (raeburn 8713:): sub hand_bubble_option {
                   8714:):     my (undef, undef, $sequence) =
                   8715:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8716:):     return if ($sequence eq '');
                   8717:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8718:):     unless (ref($navmap)) {
                   8719:):         return;
                   8720:):     }
                   8721:):     my $needs_hand_bubbles;
                   8722:):     my $map=$navmap->getResourceByUrl($sequence);
                   8723:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8724:):     foreach my $res (@resources) {
                   8725:):         if (ref($res)) {
                   8726:):             if ($res->is_problem()) {
                   8727:):                 my $partlist = $res->parts();
                   8728:):                 foreach my $part (@{ $partlist }) {
                   8729:):                     my @types = $res->responseType($part);
                   8730:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8731:):                         $needs_hand_bubbles = 1;
                   8732:):                         last;
                   8733:):                     }
                   8734:):                 }
                   8735:):             }
                   8736:):         }
                   8737:):     }
                   8738:):     if ($needs_hand_bubbles) {
          9(raebur 8739:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8740:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8741:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8742:):                &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 />').
                   8743:):                '<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 8744:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8745:):     }
                   8746:):     return;
                   8747:): }
1.423     albertel 8748: 
1.82      albertel 8749: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8750:0):     my ($r,$symb) = @_;
1.513     foxr     8751: 
1.257     albertel 8752:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8753:     if (!$symb) {
                   8754: 	return '';
                   8755:     }
1.324     albertel 8756:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8757: 
1.596.2.12.2.  9(raebur 8758:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8759:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8760:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8761:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8762:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8763:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8764:     unless (ref($navmap)) {
                   8765:         $r->print(&navmap_errormsg());
                   8766:         return '';
1.596.2.12.2.  6(raebur 8767:3):     }
1.83      albertel 8768:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8769:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8770:3):         %grader_randomlists_by_symb);
          1(raebur 8771:2):     if (ref($map)) {
                   8772:2):         $randomorder = $map->randomorder();
          6(raebur 8773:3):         $randompick = $map->randompick();
                   8774:3):     } else {
                   8775:3):         $r->print(&navmap_errormsg());
                   8776:3):         return '';
          1(raebur 8777:2):     }
          6(raebur 8778:3):     my $nav_error;
1.83      albertel 8779:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8780:3):     if ($randomorder || $randompick) {
                   8781:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8782:3):         if ($nav_error) {
                   8783:3):             $r->print(&navmap_errormsg());
                   8784:3):             return '';
1.586     raeburn  8785:         }
                   8786:     }
1.596.2.12.2.  6(raebur 8787:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8788:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8789: 
1.554     raeburn  8790:     my ($uname,$udom);
1.82      albertel 8791:     my $result= <<SCANTRONFORM;
1.81      albertel 8792: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8793:   <input type="hidden" name="command" value="scantron_configphase" />
                   8794:   $default_form_data
                   8795: SCANTRONFORM
1.82      albertel 8796:     $r->print($result);
                   8797: 
                   8798:     my @delayqueue;
1.542     raeburn  8799:     my (%completedstudents,%scandata);
1.140     albertel 8800:     
1.520     www      8801:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8802:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8803:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 8804:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8805:     $r->print('<br />');
1.140     albertel 8806:     my $start=&Time::HiRes::time();
1.158     albertel 8807:     my $i=-1;
1.542     raeburn  8808:     my $started;
1.447     foxr     8809: 
1.596.2.12.2.  (raeburn 8810:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8811:     if ($nav_error) {
                   8812:         $r->print(&navmap_errormsg());
                   8813:         return '';
                   8814:     }
                   8815: 
1.513     foxr     8816:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8817:     # the user and return.
                   8818: 
                   8819:     if ($ssi_error) {
                   8820: 	$r->print("</form>");
                   8821: 	&ssi_print_error($r);
1.520     www      8822:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8823: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8824:     }
1.447     foxr     8825: 
1.596.2.12.2.  9(raebur 8826:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8827:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8828:3):     my %orderedforcode;
1.542     raeburn  8829: 
1.157     albertel 8830:     while ($i<$scanlines->{'count'}) {
                   8831:  	($uname,$udom)=('','');
                   8832:  	$i++;
1.200     albertel 8833:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8834:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8835: 	if ($started) {
1.596.2.12.2.  1(raebur 8836:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8837: 	}
                   8838: 	$started=1;
1.596.2.12.2.  6(raebur 8839:3):         my %respnumlookup = ();
                   8840:3):         my %startline = ();
                   8841:3):         my $total;
1.157     albertel 8842:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8843:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8844:3):                                                  $randompick,$sequence,\@master_seq,
                   8845:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8846:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8847:3):                                                  \$total);
1.157     albertel 8848:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8849:  					      \%idmap,$i)) {
                   8850:   	    &scantron_add_delay(\@delayqueue,$line,
                   8851:  				'Unable to find a student that matches',1);
                   8852:  	    next;
                   8853:   	}
                   8854:  	if (exists $completedstudents{$uname}) {
                   8855:  	    &scantron_add_delay(\@delayqueue,$line,
                   8856:  				'Student '.$uname.' has multiple sheets',2);
                   8857:  	    next;
                   8858:  	}
1.596.2.12.2.  1(raebur 8859:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8860:2):         my $user = $uname.':'.$usec;
1.157     albertel 8861:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8862: 
1.596.2.12.2.  1(raebur 8863:2):         my $scancode;
                   8864:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8865:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8866:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8867:2):         } else {
                   8868:2):             $scancode = '';
                   8869:2):         }
                   8870:2): 
                   8871:2):         my @mapresources = @resources;
          6(raebur 8872:3):         if ($randomorder || $randompick) {
          1(raebur 8873:2):             @mapresources =
          6(raebur 8874:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8875:3):                              \%orderedforcode);
          1(raebur 8876:2):         }
1.586     raeburn  8877:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8878:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8879:             my $ressymb;
                   8880:             if (ref($resource)) {
                   8881:                 $ressymb = $resource->symb();
                   8882:             } else {
                   8883:                 $res_error = 1;
                   8884:                 last;
                   8885:             }
1.557     raeburn  8886:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8887:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8888:7):                 my $currcode;
                   8889:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8890:7):                     $currcode = $scancode;
                   8891:7):                 }
1.557     raeburn  8892:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8893:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8894:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8895:7):                                               $currcode);
1.557     raeburn  8896:                 $partids_by_symb{$ressymb} = $parts;
                   8897:             } else {
                   8898:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8899:             }
1.554     raeburn  8900:         }
                   8901: 
1.586     raeburn  8902:         if ($res_error) {
                   8903:             &scantron_add_delay(\@delayqueue,$line,
                   8904:                                 'An error occurred while grading student '.$uname,2);
                   8905:             next;
                   8906:         }
                   8907: 
1.330     albertel 8908: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8909:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8910: 
                   8911: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8912: 	    &scantron_putfile($scanlines,$scan_data);
                   8913: 	}
1.161     albertel 8914: 	
1.542     raeburn  8915:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8916:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8917:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8918:3):                                    \%respnumlookup,\%startline) 
                   8919:3):             eq 'ssi_error') {
1.542     raeburn  8920:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8921:             $r->print("</form>");
                   8922:             &ssi_print_error($r);
                   8923:             &Apache::lonnet::remove_lock($lock);
                   8924:             return '';      # Why return ''?  Beats me.
                   8925:         }
1.513     foxr     8926: 
1.596.2.12.2.  6(raebur 8927:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8928:3):             my $parmresult =
                   8929:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8930:3):                                                        '0_examcode',2,$scancode,
                   8931:3):                                                        'string_examcode',$uname,
                   8932:3):                                                        $udom);
                   8933:3):         }
1.140     albertel 8934: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8935:         if ($env{'form.verifyrecord'}) {
                   8936:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8937:3):             if ($randompick) {
                   8938:3):                 if ($total) {
                   8939:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8940:3):                 }
                   8941:3):             }
                   8942:3): 
1.542     raeburn  8943:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8944:             chomp($studentdata);
                   8945:             $studentdata =~ s/\r$//;
                   8946:             my $studentrecord = '';
                   8947:             my $counter = -1;
1.596.2.12.2.  1(raebur 8948:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8949:                 my $ressymb = $resource->symb();
1.542     raeburn  8950:                 ($counter,my $recording) =
                   8951:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8952:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8953:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8954:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8955:                 $studentrecord .= $recording;
                   8956:             }
                   8957:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8958:                 &Apache::lonxml::clear_problem_counter();
                   8959:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8960:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8961:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8962:3):                                            \%respnumlookup,\%startline)
                   8963:3):                     eq 'ssi_error') {
1.554     raeburn  8964:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8965:                     $r->print("</form>");
                   8966:                     &ssi_print_error($r);
                   8967:                     &Apache::lonnet::remove_lock($lock);
                   8968:                     delete($completedstudents{$uname});
                   8969:                     return '';
                   8970:                 }
1.542     raeburn  8971:                 $counter = -1;
                   8972:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8973:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8974:                     my $ressymb = $resource->symb();
1.542     raeburn  8975:                     ($counter,my $recording) =
                   8976:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8977:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8978:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8979:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8980:3):                                                  \%startline);
1.542     raeburn  8981:                     $studentrecord .= $recording;
                   8982:                 }
                   8983:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8984:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8985:                     if ($scancode eq '') {
1.596.2.6  raeburn  8986:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8987:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8988:                     } else {
1.596.2.6  raeburn  8989:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8990:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8991:                     }
                   8992:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8993:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8994:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8995:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8996:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8997:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8998:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8999:                               &Apache::loncommon::end_data_table_row().
                   9000:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9001:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9002:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9003:                               &Apache::loncommon::end_data_table_row().
                   9004:                               &Apache::loncommon::end_data_table().'</p>');
                   9005:                 } else {
                   9006:                     $r->print('<br /><span class="LC_warning">'.
                   9007:                              &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 />'.
                   9008:                              &mt("As a consequence, this user's submission history records two tries.").
                   9009:                                  '</span><br />');
                   9010:                 }
                   9011:             }
                   9012:         }
1.543     raeburn  9013:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9014:     } continue {
1.330     albertel 9015: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9016: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9017:     }
1.140     albertel 9018:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9019:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9020: #    my $lasttime = &Time::HiRes::time()-$start;
                   9021: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9022: 
1.200     albertel 9023:     $r->print("</form>");
1.157     albertel 9024:     return '';
1.75      albertel 9025: }
1.157     albertel 9026: 
1.557     raeburn  9027: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9028:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9029:):         $bubbles_per_row) = @_;
1.557     raeburn  9030:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9031:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9032:         foreach my $resource (@{$resources}) {
                   9033:             my $ressymb = $resource->symb();
                   9034:             my ($analysis,$parts) =
                   9035:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9036:):                                           $env{'user.name'},$env{'user.domain'},
                   9037:):                                           1,$bubbles_per_row);
1.557     raeburn  9038:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9039:             if (ref($analysis) eq 'HASH') {
                   9040:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9041:                     $grader_randomlists_by_symb->{$ressymb} =
                   9042:                         $analysis->{'parts_withrandomlist'};
                   9043:                 }
                   9044:             }
                   9045:         }
                   9046:     }
                   9047:     return;
                   9048: }
                   9049: 
1.596.2.12.2.  1(raebur 9050:2): =pod
                   9051:2): 
                   9052:2): =item users_order
                   9053:2): 
                   9054:2):   Returns array of resources in current map, ordered based on either CODE,
                   9055:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9056:2):   "NAMEd" exam.
                   9057:2): 
          6(raebur 9058:3):   Should be used when randomorder and/or randompick applied when the 
                   9059:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9060:3):   for the version of the exam the student received.
          1(raebur 9061:2): 
                   9062:2): =cut
                   9063:2): 
                   9064:2): sub users_order  {
          6(raebur 9065:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9066:2):     my @mapresources;
          6(raebur 9067:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9068:2):         return @mapresources;
                   9069:2):     }
          6(raebur 9070:3):     if ($scancode) {
                   9071:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9072:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9073:3):         } else {
                   9074:3):             $env{'form.CODE'} = $scancode;
                   9075:3):             my $actual_seq =
                   9076:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9077:3):                                                                $master_seq,
                   9078:3):                                                                $user,$scancode,1);
                   9079:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9080:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9081:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9082:3):                     if (@mapresources > 0) {
                   9083:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9084:3):                     }
                   9085:3):                 }
                   9086:3):             }
                   9087:3):             delete($env{'form.CODE'});
          1(raebur 9088:2):         }
                   9089:2):     } else {
                   9090:2):         my $actual_seq =
                   9091:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9092:2):                                                            $master_seq,
          5(raebur 9093:3):                                                            $user,undef,1);
          1(raebur 9094:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9095:2):             @mapresources =
                   9096:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9097:2):         }
          6(raebur 9098:3):     }
                   9099:3):     return @mapresources;
          1(raebur 9100:2): }
                   9101:2): 
1.542     raeburn  9102: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9103:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9104:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9105:3):     my $uselookup = 0;
                   9106:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9107:3):         (ref($startline) eq 'HASH')) {
                   9108:3):         $uselookup = 1;
                   9109:3):     }
                   9110:3): 
1.554     raeburn  9111:     if (ref($resources) eq 'ARRAY') {
                   9112:         my $count = 0;
                   9113:         foreach my $resource (@{$resources}) {
                   9114:             my $ressymb = $resource->symb();
                   9115:             my %form = ('submitted'      => 'scantron',
                   9116:                         'grade_target'   => 'grade',
                   9117:                         'grade_username' => $uname,
                   9118:                         'grade_domain'   => $udom,
                   9119:                         'grade_courseid' => $env{'request.course.id'},
                   9120:                         'grade_symb'     => $ressymb,
                   9121:                         'CODE'           => $scancode
                   9122:                        );
1.596.2.12.2.  (raeburn 9123:):             if ($bubbles_per_row ne '') {
                   9124:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9125:):             }
                   9126:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9127:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9128:):             }
1.554     raeburn  9129:             if (ref($parts) eq 'HASH') {
                   9130:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9131:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9132:3):                         if ($uselookup) {
                   9133:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9134:3):                         } else {
                   9135:3):                             $form{'scantron_questnum_start.'.$part} =
                   9136:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9137:3):                         }
1.554     raeburn  9138:                         $count++;
                   9139:                     }
                   9140:                 }
                   9141:             }
                   9142:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9143:             return 'ssi_error' if ($ssi_error);
                   9144:             last if (&Apache::loncommon::connection_aborted($r));
                   9145:         }
1.542     raeburn  9146:     }
                   9147:     return;
                   9148: }
                   9149: 
1.157     albertel 9150: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9151:0):     my ($r,$symb) = @_;
1.565     raeburn  9152:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9153:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9154:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9155:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9156:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9157: 							  'domainid',
1.565     raeburn  9158: 							  'coursename',$dom);
                   9159:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9160:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9161:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9162:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9163:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9164:     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 9165:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9166:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9167:     function checkUpload(formname) {
                   9168: 	if (formname.upfile.value == "") {
1.579     raeburn  9169: 	    alert("'.$nofile_alert.'");
1.157     albertel 9170: 	    return false;
                   9171: 	}
1.565     raeburn  9172:         if (formname.courseid.value == "") {
1.579     raeburn  9173:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9174:             return false;
                   9175:         }
1.157     albertel 9176: 	formname.submit();
                   9177:     }
1.565     raeburn  9178: 
                   9179:     function ToSyllabus() {
                   9180:         var cdom = '."'$dom'".';
                   9181:         var cnum = document.rules.courseid.value;
                   9182:         if (cdom == "" || cdom == null) {
                   9183:             return;
                   9184:         }
                   9185:         if (cnum == "" || cnum == null) {
                   9186:            return;
                   9187:         }
                   9188:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9189:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9190:         return;
                   9191:     }
                   9192: 
1.596.2.12.2.  9(raebur 9193:9):     '.$formatjs.'
                   9194:9): '));
                   9195:9):     $r->print('
1.596.2.4  raeburn  9196: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9197: 
1.492     albertel 9198: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9199: '.$default_form_data.
                   9200:   &Apache::lonhtmlcommon::start_pick_box().
                   9201:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9202:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9203:   &Apache::lonhtmlcommon::row_closure().
                   9204:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9205:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9206:   &Apache::lonhtmlcommon::row_closure().
                   9207:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9208:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9209:9):   &Apache::lonhtmlcommon::row_closure());
                   9210:9):     if ($formatoptions) {
                   9211:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9212:9):                   &Apache::lonhtmlcommon::row_closure());
                   9213:9):     }
                   9214:9):     $r->print(
1.565     raeburn  9215:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9216:   '<input type="file" name="upfile" size="50" />'.
                   9217:   &Apache::lonhtmlcommon::row_closure(1).
                   9218:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9219: 
1.492     albertel 9220: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9221: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9222: </form>
1.492     albertel 9223: ');
1.157     albertel 9224:     return '';
                   9225: }
                   9226: 
1.596.2.12.2.  9(raebur 9227:9): sub scantron_upload_dataformat {
                   9228:9):     my ($dom) = @_;
                   9229:9):     my ($formatoptions,$formattitle,$formatjs);
                   9230:9):     $formatjs = <<'END';
                   9231:9): function toggleScantab(form) {
                   9232:9):    return;
                   9233:9): }
                   9234:9): END
                   9235:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9236:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9237:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9238:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9239:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9240:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9241:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9242:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9243:9):                             my ($onclick,$formatextra,$singleline);
                   9244:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9245:9):                             my $count = 0;
                   9246:9):                             foreach my $line (@lines) {
                   9247:9):                                 next if ($line =~ /^#/);
                   9248:9):                                 $singleline = $line;
                   9249:9):                                 $count ++;
                   9250:9):                             }
                   9251:9):                             if ($count > 1) {
                   9252:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9253:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9254:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9255:9):                                                &scantron_scantab().'</span></div>';
                   9256:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9257:9):                                 $formatjs = <<"END";
                   9258:9): function toggleScantab(form) {
                   9259:9):     var divid = 'bubbletype';
                   9260:9):     if (document.getElementById(divid)) {
                   9261:9):         var radioname = 'fileformat';
                   9262:9):         var num = form.elements[radioname].length;
                   9263:9):         if (num) {
                   9264:9):             for (var i=0; i<num; i++) {
                   9265:9):                 if (form.elements[radioname][i].checked) {
                   9266:9):                     var chosen = form.elements[radioname][i].value;
                   9267:9):                     if (chosen == 'dat') {
                   9268:9):                         document.getElementById(divid).style.display = 'none';
                   9269:9):                     } else if (chosen == 'csv') {
                   9270:9):                         document.getElementById(divid).style.display = 'block';
                   9271:9):                     }
                   9272:9):                 }
                   9273:9):             }
                   9274:9):         }
                   9275:9):     }
                   9276:9):     return;
                   9277:9): }
                   9278:9): 
                   9279:9): END
                   9280:9):                             } elsif ($count == 1) {
                   9281:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9282:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9283:9):                             }
                   9284:9):                             $formattitle = &mt('File format');
                   9285:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9286:9):                                              &mt('Plain Text (no delimiters)').
                   9287:9):                                              '</label>'.('&nbsp;'x2).
                   9288:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9289:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9290:9):                         }
                   9291:9):                     }
                   9292:9):                 }
                   9293:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9294:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9295:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9296:9):                         $formattitle = &mt('Bubblesheet type');
                   9297:9):                         $formatoptions = &scantron_scantab();
                   9298:9):                     }
                   9299:9):                 }
                   9300:9):             }
                   9301:9):         }
                   9302:9):     }
                   9303:9):     return ($formatoptions,$formattitle,$formatjs);
                   9304:9): }
1.423     albertel 9305: 
1.157     albertel 9306: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9307:0):     my ($r,$symb) = @_;
1.182     albertel 9308:     my $doanotherupload=
                   9309: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9310: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9311: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9312: 	'</form>'."\n";
1.257     albertel 9313:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9314: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9315: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9316: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9317:0):         unless ($symb) {
1.182     albertel 9318: 	    $r->print($doanotherupload);
                   9319: 	}
1.162     albertel 9320: 	return '';
                   9321:     }
1.257     albertel 9322:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9323:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9324:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9325:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9326:3):         $r->print(
                   9327:3):             &Apache::lonhtmlcommon::confirm_success(
                   9328:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9329:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9330:     } else {
1.596.2.12.2.  9(raebur 9331:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9332:9):         my $parser;
                   9333:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9334:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9335:9):                 my $is_csv;
                   9336:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9337:9):                 if (@possibles > 1) {
                   9338:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9339:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9340:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9341:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9342:9):                                     $is_csv = 1;
                   9343:9):                                 }
                   9344:9):                             }
                   9345:9):                         }
                   9346:9):                     }
                   9347:9):                 } elsif (@possibles == 1) {
                   9348:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9349:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9350:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9351:9):                                 $is_csv = 1;
                   9352:9):                             }
                   9353:9):                         }
                   9354:9):                     }
                   9355:9):                 }
                   9356:9):                 if ($is_csv) {
                   9357:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9358:9):                 }
                   9359:9):             }
                   9360:9):         }
                   9361:9):         my $result =
                   9362:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9363:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9364: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9365:3):             $r->print(
                   9366:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9367:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9368:3):                         (length($env{'form.upfile'})-1),
                   9369:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9370:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9371:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9372:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9373: 	} else {
1.596.2.12.2.  5(raebur 9374:3):             $r->print(
                   9375:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9376:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9377:3):                           $result,
1.568     raeburn  9378: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9379: 	}
                   9380:     }
1.174     albertel 9381:     if ($symb) {
1.596.2.12.2.  1(raebur 9382:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9383:     } else {
1.182     albertel 9384: 	$r->print($doanotherupload);
1.174     albertel 9385:     }
1.157     albertel 9386:     return '';
                   9387: }
                   9388: 
1.567     raeburn  9389: sub validate_uploaded_scantron_file {
                   9390:     my ($cdom,$cname,$fname) = @_;
                   9391:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9392:     my @lines;
                   9393:     if ($scanlines ne '-1') {
                   9394:         @lines=split("\n",$scanlines,-1);
                   9395:     }
                   9396:     my $output;
                   9397:     if (@lines) {
                   9398:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9399:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9400:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9401:         my %idmap = &username_to_idmap($classlist);
                   9402:         foreach my $key (keys(%idmap)) {
                   9403:             my $lckey = lc($key);
                   9404:             $idmap{$lckey} = $idmap{$key};
                   9405:         }
                   9406:         my %unique_formats;
1.596.2.12.2.  9(raebur 9407:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9408:         foreach my $line (@formatlines) {
                   9409:             chomp($line);
                   9410:             my @config = split(/:/,$line);
                   9411:             my $idstart = $config[5];
                   9412:             my $idlength = $config[6];
                   9413:             if (($idstart ne '') && ($idlength > 0)) {
                   9414:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9415:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9416:                 } else {
                   9417:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9418:                 }
                   9419:             }
                   9420:         }
                   9421:         foreach my $key (keys(%unique_formats)) {
                   9422:             my ($idstart,$idlength) = split(':',$key);
                   9423:             %{$counts{$key}} = (
                   9424:                                'found'   => 0,
                   9425:                                'total'   => 0,
                   9426:                               );
                   9427:             foreach my $line (@lines) {
                   9428:                 next if ($line =~ /^#/);
                   9429:                 next if ($line =~ /^[\s\cz]*$/);
                   9430:                 my $id = substr($line,$idstart-1,$idlength);
                   9431:                 $id = lc($id);
                   9432:                 if (exists($idmap{$id})) {
                   9433:                     $counts{$key}{'found'} ++;
                   9434:                 }
                   9435:                 $counts{$key}{'total'} ++;
                   9436:             }
                   9437:             if ($counts{$key}{'total'}) {
                   9438:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9439:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9440:                     $max_match_pct = $percent_match;
                   9441:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9442:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9443:                     $max_match_count = $counts{$key}{'total'};
                   9444:                 }
                   9445:             }
                   9446:         }
                   9447:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9448:             my $format_descs;
                   9449:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9450:             for (my $i=0; $i<$numwithformat; $i++) {
                   9451:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9452:                 if ($i<$numwithformat-2) {
                   9453:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9454:                 } elsif ($i==$numwithformat-2) {
                   9455:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9456:                 } elsif ($i==$numwithformat-1) {
                   9457:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9458:                 }
                   9459:             }
                   9460:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9461:3):             $output .= '<br />';
                   9462:3):             if ($found_match_count == $max_match_count) {
                   9463:3):                 # 100% matching entries
                   9464:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9465:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9466:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9467:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9468:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9469:3):                     ' in the file (for the format defined for [_3]).',
                   9470:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9471:3):             } else {
                   9472:3):                 # Not all entries matching? -> Show warning and additional info
                   9473:3):                 $output .=
                   9474:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9475:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9476:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9477:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9478:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9479:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9480:3):                         ' in the file (for the format defined for [_3]).',
                   9481:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9482:3):                     '<p class="LC_info">'.
                   9483:3):                     &mt('A low percentage of matches results from one of the following:').
                   9484:3):                     '</p><ul>'.
                   9485:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9486:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9487:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9488:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9489:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9490:3):                     '</ul>';
                   9491:3):             }
1.567     raeburn  9492:         }
                   9493:     } else {
1.596.2.12.2.  5(raebur 9494:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9495:     }
                   9496:     return $output;
                   9497: }
                   9498: 
1.202     albertel 9499: sub valid_file {
                   9500:     my ($requested_file)=@_;
                   9501:     foreach my $filename (sort(&scantron_filenames())) {
                   9502: 	if ($requested_file eq $filename) { return 1; }
                   9503:     }
                   9504:     return 0;
                   9505: }
                   9506: 
                   9507: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9508:0):     my ($r,$symb) = @_;
          (raeburn 9509:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9510:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9511:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9512:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9513:     if (! &valid_file($file)) {
1.492     albertel 9514: 	$r->print('
1.202     albertel 9515: 	<p>
1.596.2.12.2.  3(raebur 9516:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9517:         </p>
1.492     albertel 9518: ');
1.202     albertel 9519: 	return;
                   9520:     }
                   9521:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9522:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9523:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9524:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9525:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9526:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9527:     $r->print('
1.202     albertel 9528:     <p>
1.596.2.12.2.  1(raebur 9529:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9530: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9531:     </p>
                   9532:     <p>
1.492     albertel 9533: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9534: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9535:     </p>
                   9536:     <p>
1.492     albertel 9537: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9538: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9539:     </p>
1.492     albertel 9540: ');
1.202     albertel 9541:     return '';
                   9542: }
1.157     albertel 9543: 
1.523     raeburn  9544: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9545:0):     my ($r,$symb) = @_;
1.523     raeburn  9546:     if (!$symb) {return '';}
                   9547:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9548:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9549:     my $numletts = scalar(keys(%lettdig));
                   9550:     my $cnum = $env{'course.'.$cid.'.num'};
                   9551:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9552:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9553:     my %record;
                   9554:     my %scantron_config =
1.596.2.12.2.  9(raebur 9555:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9556:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9557:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9558:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9559:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9560:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9561:     unless (ref($navmap)) {
                   9562:         $r->print(&navmap_errormsg());
                   9563:         return '';
                   9564:     }
1.523     raeburn  9565:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9566:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9567:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9568:2):     if (ref($map)) {
                   9569:2):         $randomorder=$map->randomorder();
          7(raebur 9570:3):         $randompick=$map->randompick();
          1(raebur 9571:2):     }
1.557     raeburn  9572:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9573:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9574:3):     if ($nav_error) {
                   9575:3):         $r->print(&navmap_errormsg());
                   9576:3):         return '';
          1(raebur 9577:2):     }
          (raeburn 9578:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9579:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9580:     my ($uname,$udom);
1.523     raeburn  9581:     my (%scandata,%lastname,%bylast);
                   9582:     $r->print('
                   9583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9584: 
                   9585:     my @delayqueue;
                   9586:     my %completedstudents;
                   9587: 
1.596.2.12.2.  6(raebur 9588:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9589:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9590:3):     my ($username,$domain,$started);
          (raeburn 9591:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9592:     if ($nav_error) {
                   9593:         $r->print(&navmap_errormsg());
                   9594:         return '';
                   9595:     }
1.523     raeburn  9596: 
                   9597:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9598:                                           'Processing first student');
                   9599:     my $start=&Time::HiRes::time();
                   9600:     my $i=-1;
                   9601: 
                   9602:     while ($i<$scanlines->{'count'}) {
                   9603:         ($username,$domain,$uname)=('','','');
                   9604:         $i++;
                   9605:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9606:         if ($line=~/^[\s\cz]*$/) { next; }
                   9607:         if ($started) {
                   9608:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9609:                                                      'last student');
                   9610:         }
                   9611:         $started=1;
                   9612:         my $scan_record=
                   9613:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9614:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9615:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9616:3):                                               \%idmap,$i)) {
1.523     raeburn  9617:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9618:                                 'Unable to find a student that matches',1);
                   9619:             next;
                   9620:         }
                   9621:         if (exists $completedstudents{$uname}) {
                   9622:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9623:                                 'Student '.$uname.' has multiple sheets',2);
                   9624:             next;
                   9625:         }
                   9626:         my $pid = $scan_record->{'scantron.ID'};
                   9627:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9628:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9629:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9630:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9631:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9632:2): 
                   9633:2):         my $scancode;
                   9634:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9635:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9636:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9637:2):         } else {
                   9638:2):             $scancode = '';
                   9639:2):         }
                   9640:2): 
                   9641:2):         my @mapresources = @resources;
          6(raebur 9642:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9643:3):         my %respnumlookup=();
                   9644:3):         my %startline=();
                   9645:3):         if ($randomorder || $randompick) {
          1(raebur 9646:2):             @mapresources =
          6(raebur 9647:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9648:3):                              \%orderedforcode);
                   9649:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9650:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9651:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9652:3):                                              \%respnumlookup,\%startline);
                   9653:3):             if ($randompick && $total) {
                   9654:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9655:3):             }
          1(raebur 9656:2):         }
          6(raebur 9657:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9658:3):         chomp($scandata{$pid});
                   9659:3):         $scandata{$pid} =~ s/\r$//;
                   9660:3): 
1.523     raeburn  9661:         my $counter = -1;
1.596.2.12.2.  1(raebur 9662:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9663:             my $parts;
1.554     raeburn  9664:             my $ressymb = $resource->symb();
1.557     raeburn  9665:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9666:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9667:7):                 my $currcode;
                   9668:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9669:7):                     $currcode = $scancode;
                   9670:7):                 }
1.557     raeburn  9671:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9672:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9673:):                                               $username,$domain,undef,
          1(raebur 9674:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9675:             } else {
                   9676:                 $parts = $grader_partids_by_symb{$ressymb};
                   9677:             }
1.542     raeburn  9678:             ($counter,my $recording) =
                   9679:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9680:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9681:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9682:3):                                          $randomorder,$randompick,
                   9683:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9684:             $record{$pid} .= $recording;
1.523     raeburn  9685:         }
                   9686:     }
                   9687:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9688:     $r->print('<br />');
                   9689:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9690:     $passed = 0;
                   9691:     $failed = 0;
                   9692:     $numstudents = 0;
                   9693:     foreach my $last (sort(keys(%bylast))) {
                   9694:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9695:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9696:                 my $showscandata = $scandata{$pid};
                   9697:                 my $showrecord = $record{$pid};
                   9698:                 $showscandata =~ s/\s/&nbsp;/g;
                   9699:                 $showrecord =~ s/\s/&nbsp;/g;
                   9700:                 if ($scandata{$pid} eq $record{$pid}) {
                   9701:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9702:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9703: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9704: '</tr>'."\n".
                   9705: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9706:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9707:                     $passed ++;
                   9708:                 } else {
                   9709:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9710:                     $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  9711: '</tr>'."\n".
                   9712: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9713:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9714: '</tr>'."\n";
                   9715:                     $failed ++;
                   9716:                 }
                   9717:                 $numstudents ++;
                   9718:             }
                   9719:         }
                   9720:     }
1.596.2.4  raeburn  9721:     $r->print('<p>'.
1.596.2.8  raeburn  9722:               &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  9723:                   '<b>',
                   9724:                   $numstudents,
                   9725:                   '</b>',
                   9726:                   $env{'form.scantron_maxbubble'}).
                   9727:               '</p>'
                   9728:     );
1.596.2.12.2.  2(raebur 9729:2):     $r->print('<p>'
                   9730:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9731:2):              .'<br />'
                   9732:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9733:2):              .'</p>');
1.523     raeburn  9734:     if ($passed) {
1.572     www      9735:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9736:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9737:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9738:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9739:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9740:                  $okstudents."\n".
                   9741:                  &Apache::loncommon::end_data_table().'<br />');
                   9742:     }
                   9743:     if ($failed) {
1.572     www      9744:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9745:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9746:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9747:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9748:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9749:                  $badstudents."\n".
                   9750:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9751:                  &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  9752:     }
1.596.2.12.2.  1(raebur 9753:0):     $r->print('</form><br />');
1.523     raeburn  9754:     return;
                   9755: }
                   9756: 
1.542     raeburn  9757: sub verify_scantron_grading {
1.554     raeburn  9758:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9759:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9760:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9761:     my ($record,%expected,%startpos);
                   9762:     return ($counter,$record) if (!ref($resource));
                   9763:     return ($counter,$record) if (!$resource->is_problem());
                   9764:     my $symb = $resource->symb();
1.554     raeburn  9765:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9766:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9767:         $counter ++;
                   9768:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9769:3):         my $respnum = $counter;
                   9770:3):         if ($randomorder || $randompick) {
                   9771:3):             $respnum = $respnumlookup->{$counter};
                   9772:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9773:3):         } else {
                   9774:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9775:3):         }
                   9776:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9777:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9778:             foreach my $item (@sub_lines) {
                   9779:                 $expected{$part_id} += $item;
                   9780:             }
                   9781:         } else {
1.596.2.12.2.  6(raebur 9782:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9783:         }
                   9784:     }
                   9785:     if ($symb) {
                   9786:         my %recorded;
                   9787:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9788:         if ($returnhash{'version'}) {
                   9789:             my %lasthash=();
                   9790:             my $version;
                   9791:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9792:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9793:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9794:                 }
                   9795:             }
                   9796:             foreach my $key (keys(%lasthash)) {
                   9797:                 if ($key =~ /\.scantron$/) {
                   9798:                     my $value = &unescape($lasthash{$key});
                   9799:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9800:                     if ($value eq '') {
                   9801:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9802:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9803:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9804:                             }
                   9805:                         }
                   9806:                     } else {
                   9807:                         my @tocheck;
                   9808:                         my @items = split(//,$value);
                   9809:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9810:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9811:                             if (@items < $expected{$part_id}) {
                   9812:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9813:                                 my @singles = split(//,$fragment);
                   9814:                                 foreach my $pos (@singles) {
                   9815:                                     if ($pos eq ' ') {
                   9816:                                         push(@tocheck,$pos);
                   9817:                                     } else {
                   9818:                                         my $next = shift(@items);
                   9819:                                         push(@tocheck,$next);
                   9820:                                     }
                   9821:                                 }
                   9822:                             } else {
                   9823:                                 @tocheck = @items;
                   9824:                             }
                   9825:                             foreach my $letter (@tocheck) {
                   9826:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9827:                                     if ($letter !~ /^[A-J]$/) {
                   9828:                                         $letter = $scantron_config->{'Qoff'};
                   9829:                                     }
                   9830:                                     $recorded{$part_id} .= $letter;
                   9831:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9832:                                     my $digit;
                   9833:                                     if ($letter !~ /^[A-J]$/) {
                   9834:                                         $digit = $scantron_config->{'Qoff'};
                   9835:                                     } else {
                   9836:                                         $digit = $lettdig->{$letter};
                   9837:                                     }
                   9838:                                     $recorded{$part_id} .= $digit;
                   9839:                                 }
                   9840:                             }
                   9841:                         } else {
                   9842:                             @tocheck = @items;
                   9843:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9844:                                 my $curr_sub = shift(@tocheck);
                   9845:                                 my $digit;
                   9846:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9847:                                     $digit = $lettdig->{$curr_sub}-1;
                   9848:                                 }
                   9849:                                 if ($curr_sub eq 'J') {
                   9850:                                     $digit += scalar($numletts);
                   9851:                                 }
                   9852:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9853:                                     if ($j == $digit) {
                   9854:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9855:                                     } else {
                   9856:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9857:                                     }
                   9858:                                 }
                   9859:                             }
                   9860:                         }
                   9861:                     }
                   9862:                 }
                   9863:             }
                   9864:         }
1.554     raeburn  9865:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9866:             if ($recorded{$part_id} eq '') {
                   9867:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9868:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9869:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9870:                     }
                   9871:                 }
                   9872:             }
                   9873:             $record .= $recorded{$part_id};
                   9874:         }
                   9875:     }
                   9876:     return ($counter,$record);
                   9877: }
                   9878: 
1.75      albertel 9879: #-------- end of section for handling grading scantron forms -------
                   9880: #
                   9881: #-------------------------------------------------------------------
                   9882: 
1.72      ng       9883: #-------------------------- Menu interface -------------------------
                   9884: #
1.596.2.12.2.  (raeburn 9885:): #--- Href with symb and command ---
                   9886:): 
                   9887:): sub href_symb_cmd {
                   9888:):     my ($symb,$cmd)=@_;
                   9889:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9890:): }
                   9891:): 
1.443     banghart 9892: sub grading_menu {
1.596.2.12.2.  1(raebur 9893:0):     my ($request,$symb) = @_;
1.443     banghart 9894:     if (!$symb) {return '';}
                   9895: 
                   9896:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 9897:0):                   'command'=>'individual');
                   9898:0): 
                   9899:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9900:0): 
                   9901:0):     $fields{'command'}='ungraded';
                   9902:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9903:0): 
                   9904:0):     $fields{'command'}='table';
                   9905:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9906:0): 
                   9907:0):     $fields{'command'}='all_for_one';
                   9908:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9909:0): 
                   9910:0):     $fields{'command'}='downloadfilesselect';
                   9911:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9912:     
1.443     banghart 9913:     $fields{'command'} = 'csvform';
1.538     schulted 9914:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9915:     
1.443     banghart 9916:     $fields{'command'} = 'processclicker';
1.538     schulted 9917:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9918:     
1.443     banghart 9919:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9920:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 9921:0): 
                   9922:0):     $fields{'command'} = 'initialverifyreceipt';
                   9923:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 9924:1): 
                   9925:1):     my %permissions;
                   9926:1):     if ($perm{'mgr'}) {
                   9927:1):         $permissions{'either'} = 'F';
                   9928:1):         $permissions{'mgr'} = 'F';
                   9929:1):     }
                   9930:1):     if ($perm{'vgr'}) {
                   9931:1):         $permissions{'either'} = 'F';
                   9932:1):         $permissions{'vgr'} = 'F';
                   9933:1):     }
                   9934:1): 
          1(raebur 9935:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9936:             items =>[
1.596.2.12.2.  1(raebur 9937:0):                         {       linktext => 'Select individual students to grade',
                   9938:0):                                 url => $url1a,
          6(raebur 9939:1):                                 permission => $permissions{'either'},
          1(raebur 9940:0):                                 icon => 'grade_students.png',
                   9941:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   9942:0):                         },
                   9943:0):                         {       linktext => 'Grade ungraded submissions',
                   9944:0):                                 url => $url1b,
          6(raebur 9945:1):                                 permission => $permissions{'either'},
          1(raebur 9946:0):                                 icon => 'ungrade_sub.png',
                   9947:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   9948:0):                         },
                   9949:0): 
                   9950:0):                         {       linktext => 'Grading table',
                   9951:0):                                 url => $url1c,
          6(raebur 9952:1):                                 permission => $permissions{'either'},
          1(raebur 9953:0):                                 icon => 'grading_table.png',
                   9954:0):                                 linktitle => 'Grade current resource for all students.'
                   9955:0):                         },
                   9956:0):                         {       linktext => 'Grade page/folder for one student',
                   9957:0):                                 url => $url1d,
          6(raebur 9958:1):                                 permission => $permissions{'either'},
          1(raebur 9959:0):                                 icon => 'grade_PageFolder.png',
                   9960:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 9961:                         },
1.596.2.12.2.  3(raebur 9962:0):                         {       linktext => 'Download submitted files',
          1(raebur 9963:0):                                 url => $url1e,
          6(raebur 9964:1):                                 permission => $permissions{'either'},
          1(raebur 9965:0):                                 icon => 'download_sub.png',
          3(raebur 9966:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 9967:0):                         }]},
                   9968:0):                          { categorytitle=>'Automated Grading',
                   9969:0):                items =>[
                   9970:0): 
1.538     schulted 9971:                 	    {	linktext => 'Upload Scores',
                   9972:                     		url => $url2,
1.596.2.12.2.  6(raebur 9973:1):                     		permission => $permissions{'mgr'},
1.538     schulted 9974:                     		icon => 'uploadscores.png',
                   9975:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9976:                 	    },
                   9977:                 	    {	linktext => 'Process Clicker',
                   9978:                     		url => $url3,
1.596.2.12.2.  6(raebur 9979:1):                     		permission => $permissions{'mgr'},
1.538     schulted 9980:                     		icon => 'addClickerInfoFile.png',
                   9981:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9982:                 	    },
1.587     raeburn  9983:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9984:                     		url => $url4,
1.596.2.12.2.  6(raebur 9985:1):                     		permission => $permissions{'mgr'},
          1(raebur 9986:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  9987:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 9988:0):                 	    },
                   9989:0):                             {   linktext => 'Verify Receipt Number',
                   9990:0):                                 url => $url5,
          6(raebur 9991:1):                                 permission => $permissions{'either'},
          1(raebur 9992:0):                                 icon => 'receipt_number.png',
                   9993:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9994:0):                             }
                   9995:0): 
1.538     schulted 9996:                     ]
                   9997:             });
                   9998: 
1.443     banghart 9999:     # Create the menu
                   10000:     my $Str;
1.445     banghart 10001:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10002:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10003:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10004: 
1.596.2.12.2.  1(raebur 10005:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10006:     return $Str;    
                   10007: }
                   10008: 
1.596.2.12.2.  1(raebur 10009:0): sub ungraded {
                   10010:0):     my ($request)=@_;
                   10011:0):     &submit_options($request);
                   10012:0): }
1.443     banghart 10013: 
1.596.2.12.2.  1(raebur 10014:0): sub submit_options_sequence {
                   10015:0):     my ($request,$symb) = @_;
1.72      ng       10016:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10017:0):     &commonJSfunctions($request);
                   10018:0):     my $result;
1.72      ng       10019: 
1.596.2.12.2.  1(raebur 10020:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10021:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10022:0):     $result.=&selectfield(0).
                   10023:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10024:0):             <div>
                   10025:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10026:0):             </div>
                   10027:0):         </div>
                   10028:0):   </form>';
                   10029:0):     return $result;
                   10030:0): }
                   10031:0): 
                   10032:0): sub submit_options_table {
                   10033:0):     my ($request,$symb) = @_;
                   10034:0):     if (!$symb) {return '';}
1.118     ng       10035:     &commonJSfunctions($request);
1.473     albertel 10036:     my $result;
1.596.2.12.2.  1(raebur 10037:0): 
                   10038:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10039:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10040:0): 
                   10041:0):     $result.=&selectfield(1).
                   10042:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10043:0):             <div>
                   10044:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10045:0):             </div>
                   10046:0):         </div>
                   10047:0):   </form>';
                   10048:0):     return $result;
                   10049:0): }
                   10050:0): 
                   10051:0): sub submit_options_download {
                   10052:0):     my ($request,$symb) = @_;
                   10053:0):     if (!$symb) {return '';}
                   10054:0): 
                   10055:0):     my $res_error;
                   10056:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10057:0):         &response_type($symb,\$res_error);
                   10058:0):     if ($res_error) {
                   10059:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10060:0):         return;
                   10061:0):     }
                   10062:0):     unless ($numessay) {
                   10063:0):         $request->print(&mt('No essayresponse items found'));
                   10064:0):         return;
                   10065:0):     }
                   10066:0):     my $table;
                   10067:0):     if (ref($partlist) eq 'ARRAY') {
                   10068:0):         if (scalar(@$partlist) > 1 ) {
                   10069:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10070:         }
                   10071:     }
                   10072: 
1.596.2.12.2.  1(raebur 10073:0):     &commonJSfunctions($request);
1.72      ng       10074: 
1.596.2.12.2.  1(raebur 10075:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10076:0):         $table."\n".
                   10077:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10078:     $result.='
1.533     bisitz   10079: <h2>
1.596.2.12.2.  3(raebur 10080:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          1(raebur 10081:0): </h2>'.&selectfield(1).'
                   10082:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10083:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10084:0):             </div>
                   10085:0):           </div>
                   10086:0): 
                   10087:0): 
                   10088:0):   </form>';
                   10089:0):     return $result;
                   10090:0): }
                   10091:0): 
                   10092:0): #--- Displays the submissions first page -------
                   10093:0): sub submit_options {
                   10094:0):     my ($request,$symb) = @_;
                   10095:0):     if (!$symb) {return '';}
                   10096:0): 
                   10097:0):     &commonJSfunctions($request);
                   10098:0):     my $result;
                   10099:0): 
                   10100:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10101:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10102:0):     $result.=&selectfield(1).'
                   10103:0):                 <input type="hidden" name="command" value="submission" />
                   10104:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10105:0):             </div>
                   10106:0):           </div>
                   10107:0):   </form>';
                   10108:0):     return $result;
                   10109:0): }
                   10110:0): 
                   10111:0): sub selectfield {
                   10112:0):    my ($full)=@_;
                   10113:0):    my %options =
                   10114:0):        (&substatus_options,
                   10115:0):         'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10116:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10117: 
                   10118:     <fieldset>
                   10119:       <legend>
                   10120:        '.&mt('Sections').'
                   10121:       </legend>
1.596.2.12.2.  1(raebur 10122:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10123:     </fieldset>
1.596.2.12.2.  1(raebur 10124:0): 
1.533     bisitz   10125:     <fieldset>
                   10126:       <legend>
                   10127:         '.&mt('Groups').'
                   10128:       </legend>
                   10129:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10130:     </fieldset>
1.596.2.12.2.  1(raebur 10131:0):  
1.533     bisitz   10132:     <fieldset>
                   10133:       <legend>
                   10134:         '.&mt('Access Status').'
                   10135:       </legend>
1.596.2.12.2.  1(raebur 10136:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10137:0):     </fieldset>';
                   10138:0):     if ($full) {
                   10139:0):         $result.='
1.533     bisitz   10140:     <fieldset>
                   10141:       <legend>
                   10142:         '.&mt('Submission Status').'
1.596.2.12.2.  1(raebur 10143:0):       </legend>'.
                   10144:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10145:0):    '</fieldset>';
                   10146:0):     }
                   10147:0):     $result.='</div><br />';
1.44      ng       10148:     return $result;
1.2       albertel 10149: }
                   10150: 
1.596.2.12.2.  7(raebur 10151:6): sub substatus_options {
                   10152:6):     return &Apache::lonlocal::texthash(
                   10153:6):                                       'yes'       => 'with submissions',
                   10154:6):                                       'queued'    => 'in grading queue',
                   10155:6):                                       'graded'    => 'with ungraded submissions',
                   10156:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10157:7):                                       'all'       => 'with any status',
                   10158:7):                                       );
          7(raebur 10159:6): }
                   10160:6): 
          1(raebur 10161:0): sub transtatus_options {
                   10162:0):     return &Apache::lonlocal::texthash(
                   10163:0):                                        'yes'       => 'with score transactions',
                   10164:0):                                        'incorrect' => 'with less than full credit',
                   10165:0):                                        'all'       => 'with any status',
                   10166:0):                                       );
                   10167:0): }
                   10168:0): 
1.285     albertel 10169: sub reset_perm {
                   10170:     undef(%perm);
                   10171: }
                   10172: 
                   10173: sub init_perm {
                   10174:     &reset_perm();
1.300     albertel 10175:     foreach my $test_perm ('vgr','mgr','opa') {
                   10176: 
                   10177: 	my $scope = $env{'request.course.id'};
                   10178: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10179: 
                   10180: 	    $scope .= '/'.$env{'request.course.sec'};
                   10181: 	    if ( $perm{$test_perm}=
                   10182: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10183: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10184: 	    } else {
                   10185: 		delete($perm{$test_perm});
                   10186: 	    }
1.285     albertel 10187: 	}
                   10188:     }
                   10189: }
                   10190: 
1.596.2.12.2.  (raeburn 10191:): sub init_old_essays {
                   10192:):     my ($symb,$apath,$adom,$aname) = @_;
                   10193:):     if ($symb ne '') {
                   10194:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10195:):         if (keys(%essays) > 0) {
                   10196:):             $old_essays{$symb} = \%essays;
                   10197:):         }
                   10198:):     }
                   10199:):     return;
                   10200:): }
                   10201:): 
                   10202:): sub reset_old_essays {
                   10203:):     undef(%old_essays);
                   10204:): }
                   10205:): 
1.400     www      10206: sub gather_clicker_ids {
1.408     albertel 10207:     my %clicker_ids;
1.400     www      10208: 
                   10209:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10210: 
                   10211:     # Set up a couple variables.
1.407     albertel 10212:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10213:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10214:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10215: 
1.407     albertel 10216:     foreach my $student (keys(%$classlist)) {
1.438     www      10217:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10218:         my $username = $classlist->{$student}->[$username_idx];
                   10219:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10220:         my $clickers =
1.408     albertel 10221: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10222:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10223:             $id=~s/^[\#0]+//;
1.421     www      10224:             $id=~s/[\-\:]//g;
1.407     albertel 10225:             if (exists($clicker_ids{$id})) {
1.408     albertel 10226: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10227:             } else {
1.408     albertel 10228: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10229:             }
                   10230:         }
                   10231:     }
1.407     albertel 10232:     return %clicker_ids;
1.400     www      10233: }
                   10234: 
1.402     www      10235: sub gather_adv_clicker_ids {
1.408     albertel 10236:     my %clicker_ids;
1.402     www      10237:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10238:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10239:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10240:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10241:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10242:             my ($puname,$pudom)=split(/\:/,$person);
                   10243:             my $clickers =
1.408     albertel 10244: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10245:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10246: 		$id=~s/^[\#0]+//;
1.421     www      10247:                 $id=~s/[\-\:]//g;
1.408     albertel 10248: 		if (exists($clicker_ids{$id})) {
                   10249: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10250: 		} else {
                   10251: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10252: 		}
1.405     www      10253:             }
1.402     www      10254:         }
                   10255:     }
1.407     albertel 10256:     return %clicker_ids;
1.402     www      10257: }
                   10258: 
1.413     www      10259: sub clicker_grading_parameters {
                   10260:     return ('gradingmechanism' => 'scalar',
                   10261:             'upfiletype' => 'scalar',
                   10262:             'specificid' => 'scalar',
                   10263:             'pcorrect' => 'scalar',
                   10264:             'pincorrect' => 'scalar');
                   10265: }
                   10266: 
1.400     www      10267: sub process_clicker {
1.596.2.12.2.  1(raebur 10268:0):     my ($r,$symb)=@_;
1.400     www      10269:     if (!$symb) {return '';}
                   10270:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10271:0):     $result.=&Apache::loncommon::start_data_table().
                   10272:0):              &Apache::loncommon::start_data_table_header_row().
                   10273:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10274:0):              &Apache::loncommon::end_data_table_header_row().
                   10275:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10276: # Attempt to restore parameters from last session, set defaults if not present
                   10277:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10278:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10279:                                                  \%Saveable_Parameters);
                   10280:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10281:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10282:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10283:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10284: 
                   10285:     my %checked;
1.521     www      10286:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10287:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10288:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10289:        }
                   10290:     }
                   10291: 
1.596.2.12.2.  1(raebur 10292:0):     my $upload=&mt("Evaluate File");
1.400     www      10293:     my $type=&mt("Type");
1.402     www      10294:     my $attendance=&mt("Award points just for participation");
                   10295:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10296:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10297:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10298:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10299:     my $pcorrect=&mt("Percentage points for correct solution");
                   10300:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10301:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10302:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10303:):                                                     'interwrite' => 'interwrite PRS',
                   10304:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10305:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10306:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10307: function sanitycheck() {
                   10308: // Accept only integer percentages
                   10309:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10310:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10311: // Find out grading choice
                   10312:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10313:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10314:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10315:       }
                   10316:    }
                   10317: // By default, new choice equals user selection
                   10318:    newgradingchoice=gradingchoice;
                   10319: // Not good to give more points for false answers than correct ones
                   10320:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10321:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10322:    }
                   10323: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10324:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10325:       document.forms.gradesupload.pcorrect.value=100;
                   10326:       document.forms.gradesupload.pincorrect.value=100;
                   10327:    }
                   10328: // If the values are different, cannot be attendance only
                   10329:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10330:        (gradingchoice=='attendance')) {
                   10331:        newgradingchoice='personnel';
                   10332:    }
                   10333: // Change grading choice to new one
                   10334:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10335:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10336:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10337:       } else {
                   10338:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10339:       }
                   10340:    }
                   10341: // Remember the old state
                   10342:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10343: }
1.596.2.12.2.  1(raebur 10344:0): ENDUPFORM
                   10345:0):     $result.= <<ENDUPFORM;
1.400     www      10346: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10347: <input type="hidden" name="symb" value="$symb" />
                   10348: <input type="hidden" name="command" value="processclickerfile" />
                   10349: <input type="file" name="upfile" size="50" />
                   10350: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10351:0): ENDUPFORM
                   10352:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10353:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10354:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10355: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10356: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10357: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10358: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10359: <br />&nbsp;&nbsp;&nbsp;
                   10360: <input type="text" name="givenanswer" size="50" />
1.413     www      10361: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10362:0): ENDGRADINGFORM
                   10363:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10364:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10365:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10366: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10367: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10368: </form>
1.596.2.12.2.  1(raebur 10369:0): ENDPERCFORM
                   10370:0):     $result.='</td>'.
                   10371:0):              &Apache::loncommon::end_data_table_row().
                   10372:0):              &Apache::loncommon::end_data_table();
1.400     www      10373:     return $result;
                   10374: }
                   10375: 
                   10376: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10377:0):     my ($r,$symb) = @_;
1.400     www      10378:     if (!$symb) {return '';}
1.413     www      10379: 
                   10380:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10381:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10382:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10383:0):     my $result='';
1.404     www      10384:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10385: 	$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 10386:0): 	return $result;
1.404     www      10387:     }
1.522     www      10388:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10389:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10390:0):         return $result;
1.521     www      10391:     }
1.522     www      10392:     my $foundgiven=0;
1.521     www      10393:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10394:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10395:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10396:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10397:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10398:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10399:         $foundgiven=$#answers+1;
1.521     www      10400:     }
1.407     albertel 10401:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10402:     my %correct_ids;
1.404     www      10403:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10404: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10405:     }
                   10406:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10407: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10408: 	   $correct_id=~tr/a-z/A-Z/;
                   10409: 	   $correct_id=~s/\s//gs;
                   10410: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10411:            $correct_id=~s/[\-\:]//g;
1.414     www      10412:            if ($correct_id) {
                   10413: 	      $correct_ids{$correct_id}='specified';
                   10414:            }
                   10415:         }
1.400     www      10416:     }
1.404     www      10417:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10418: 	$result.=&mt('Score based on attendance only');
1.521     www      10419:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10420:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10421:     } else {
1.408     albertel 10422: 	my $number=0;
1.411     www      10423: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10424: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10425: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10426: 	    if ($correct_ids{$id} eq 'specified') {
                   10427: 		$result.=&mt('specified');
                   10428: 	    } else {
                   10429: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10430: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10431: 	    }
                   10432: 	    $number++;
                   10433: 	}
1.411     www      10434:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10435:3):         if ($number==0) {
                   10436:3):             $result .=
                   10437:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10438:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10439:0):             return $result;
          5(raebur 10440:3):         }
1.404     www      10441:     }
1.405     www      10442:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10443:3):         $result .=
                   10444:3):             &Apache::lonhtmlcommon::confirm_success(
                   10445:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10446:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10447:0):         return $result;
1.405     www      10448:     }
1.596.2.12.2.  7(raebur 10449:9):     my $mimetype;
                   10450:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10451:9):         my $mm = new File::MMagic;
                   10452:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10453:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10454:9):             $result.= '<p>'.
                   10455:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10456:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10457:0):             return $result;
          7(raebur 10458:9):         }
                   10459:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10460:9):         $result .= '<p>'.
                   10461:9):             &Apache::lonhtmlcommon::confirm_success(
                   10462:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10463:0):         return $result;
          7(raebur 10464:9):     }
1.410     www      10465: 
                   10466: # Were able to get all the info needed, now analyze the file
                   10467: 
1.411     www      10468:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10469:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10470:0):     $result.=&Apache::loncommon::start_data_table().
                   10471:0):              &Apache::loncommon::start_data_table_header_row().
                   10472:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10473:0):              &Apache::loncommon::end_data_table_header_row().
                   10474:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10475:0): <td>
1.410     www      10476: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10477: <input type="hidden" name="symb" value="$symb" />
                   10478: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10479: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10480: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10481: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10482: ENDHEADER
1.522     www      10483:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10484:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10485:     } 
1.408     albertel 10486:     my %responses;
                   10487:     my @questiontitles;
1.405     www      10488:     my $errormsg='';
                   10489:     my $number=0;
                   10490:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10491:9):         if ($mimetype eq 'text/plain') {
                   10492:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10493:9):         } elsif ($mimetype eq 'text/html') {
                   10494:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10495:9):         }
                   10496:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10497:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10498:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10499:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10500:):     }
1.411     www      10501:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10502:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10503:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10504:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10505:              '<br />';
1.522     www      10506:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10507:        $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 10508:0):        return $result;
1.522     www      10509:     } 
1.414     www      10510: # Remember Question Titles
                   10511: # FIXME: Possibly need delimiter other than ":"
                   10512:     for (my $i=0;$i<$number;$i++) {
                   10513:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10514:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10515:     }
1.411     www      10516:     my $correct_count=0;
                   10517:     my $student_count=0;
                   10518:     my $unknown_count=0;
1.414     www      10519: # Match answers with usernames
                   10520: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10521:     foreach my $id (keys(%responses)) {
1.410     www      10522:        if ($correct_ids{$id}) {
1.414     www      10523:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10524:           $correct_count++;
1.410     www      10525:        } elsif ($clicker_ids{$id}) {
1.437     www      10526:           if ($clicker_ids{$id}=~/\,/) {
                   10527: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10528:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10529:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10530:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10531:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10532:                            "<select name='multi".$id."'>";
                   10533:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10534:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10535:              }
                   10536:              $result.='</select>';
                   10537:              $unknown_count++;
                   10538:           } else {
                   10539: # Good: found one and only one user with the right clicker
                   10540:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10541:              $student_count++;
                   10542:           }
1.410     www      10543:        } else {
1.596.2.12.2.  1(raebur 10544:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10545:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10546:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10547:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10548:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10549:                    "\n".&mt("Domain").": ".
                   10550:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10551:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10552:           $unknown_count++;
1.410     www      10553:        }
1.405     www      10554:     }
1.412     www      10555:     $result.='<hr />'.
                   10556:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10557:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10558:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10559:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10560:        } elsif ($correct_count>1) {
1.414     www      10561:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10562:        }
                   10563:     }
1.428     www      10564:     if ($number<1) {
                   10565:        $errormsg.="Found no questions.";
                   10566:     }
1.412     www      10567:     if ($errormsg) {
                   10568:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10569:     } else {
                   10570:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10571:     }
1.596.2.12.2.  1(raebur 10572:0):     $result.='</form></td>'.
                   10573:0):              &Apache::loncommon::end_data_table_row().
                   10574:0):              &Apache::loncommon::end_data_table();
                   10575:0):     return $result;
1.400     www      10576: }
                   10577: 
1.405     www      10578: sub iclicker_eval {
1.406     www      10579:     my ($questiontitles,$responses)=@_;
1.405     www      10580:     my $number=0;
                   10581:     my $errormsg='';
                   10582:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10583:         my %components=&Apache::loncommon::record_sep($line);
                   10584:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10585: 	if ($entries[0] eq 'Question') {
                   10586: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10587: 		$$questiontitles[$number]=$entries[$i];
                   10588: 		$number++;
                   10589: 	    }
                   10590: 	}
                   10591: 	if ($entries[0]=~/^\#/) {
                   10592: 	    my $id=$entries[0];
                   10593: 	    my @idresponses;
                   10594: 	    $id=~s/^[\#0]+//;
                   10595: 	    for (my $i=0;$i<$number;$i++) {
                   10596: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10597:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10598: 		push(@idresponses,$entries[$idx]);
                   10599: 	    }
                   10600: 	    $$responses{$id}=join(',',@idresponses);
                   10601: 	}
1.405     www      10602:     }
                   10603:     return ($errormsg,$number);
                   10604: }
                   10605: 
1.596.2.12.2.  7(raebur 10606:9): sub iclickerxml_eval {
                   10607:9):     my ($questiontitles,$responses)=@_;
                   10608:9):     my $number=0;
                   10609:9):     my $errormsg='';
                   10610:9):     my @state;
                   10611:9):     my %respbyid;
                   10612:9):     my $p = HTML::Parser->new
                   10613:9):     (
                   10614:9):         xml_mode => 1,
                   10615:9):         start_h =>
                   10616:9):             [sub {
                   10617:9):                  my ($tagname,$attr) = @_;
                   10618:9):                  push(@state,$tagname);
                   10619:9):                  if ("@state" eq "ssn p") {
                   10620:9):                      my $title = $attr->{qn};
                   10621:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10622:9):                      $questiontitles->[$number]=$title;
                   10623:9):                  } elsif ("@state" eq "ssn p v") {
                   10624:9):                      my $id = $attr->{id};
                   10625:9):                      my $entry = $attr->{ans};
                   10626:9):                      $id=~s/^[\#0]+//;
                   10627:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10628:9):                      $respbyid{$id}[$number] = $entry;
                   10629:9):                  }
                   10630:9):             }, "tagname, attr"],
                   10631:9):          end_h =>
                   10632:9):                [sub {
                   10633:9):                    my ($tagname) = @_;
                   10634:9):                    if ("@state" eq "ssn p") {
                   10635:9):                        $number++;
                   10636:9):                    }
                   10637:9):                    pop(@state);
                   10638:9):                 }, "tagname"],
                   10639:9):     );
                   10640:9): 
                   10641:9):     $p->parse($env{'form.upfile'});
                   10642:9):     $p->eof;
                   10643:9):     foreach my $id (keys(%respbyid)) {
                   10644:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10645:9):     }
                   10646:9):     return ($errormsg,$number);
                   10647:9): }
                   10648:9): 
1.419     www      10649: sub interwrite_eval {
                   10650:     my ($questiontitles,$responses)=@_;
                   10651:     my $number=0;
                   10652:     my $errormsg='';
1.420     www      10653:     my $skipline=1;
                   10654:     my $questionnumber=0;
                   10655:     my %idresponses=();
1.419     www      10656:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10657:         my %components=&Apache::loncommon::record_sep($line);
                   10658:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10659:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10660:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10661:         next if $skipline;
                   10662:         if ($entries[0]!=$questionnumber) {
                   10663:            $questionnumber=$entries[0];
                   10664:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10665:            $number++;
1.419     www      10666:         }
1.420     www      10667:         my $id=$entries[4];
                   10668:         $id=~s/^[\#0]+//;
1.421     www      10669:         $id=~s/^v\d*\://i;
                   10670:         $id=~s/[\-\:]//g;
1.420     www      10671:         $idresponses{$id}[$number]=$entries[6];
                   10672:     }
1.524     raeburn  10673:     foreach my $id (keys(%idresponses)) {
1.420     www      10674:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10675:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10676:     }
                   10677:     return ($errormsg,$number);
                   10678: }
                   10679: 
1.596.2.12.2.  (raeburn 10680:): sub turning_eval {
                   10681:):     my ($questiontitles,$responses)=@_;
                   10682:):     my $number=0;
                   10683:):     my $errormsg='';
                   10684:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10685:):         my %components=&Apache::loncommon::record_sep($line);
                   10686:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10687:):         if ($#entries>$number) { $number=$#entries; }
                   10688:):         my $id=$entries[0];
                   10689:):         my @idresponses;
                   10690:):         $id=~s/^[\#0]+//;
                   10691:):         unless ($id) { next; }
                   10692:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10693:):             $entries[$idx]=~s/\,/\;/g;
                   10694:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10695:):             push(@idresponses,$entries[$idx]);
                   10696:):         }
                   10697:):         $$responses{$id}=join(',',@idresponses);
                   10698:):     }
                   10699:):     for (my $i=1; $i<=$number; $i++) {
                   10700:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10701:):     }
                   10702:):     return ($errormsg,$number);
                   10703:): }
                   10704:): 
1.414     www      10705: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10706:0):     my ($r,$symb) = @_;
1.414     www      10707:     if (!$symb) {return '';}
1.416     www      10708: # See which part we are saving to
1.582     raeburn  10709:     my $res_error;
                   10710:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10711:     if ($res_error) {
                   10712:         return &navmap_errormsg();
                   10713:     }
1.416     www      10714: # FIXME: This should probably look for the first handgradeable part
                   10715:     my $part=$$partlist[0];
                   10716: # Start screen output
1.596.2.12.2.  1(raebur 10717:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10718:0):                  &Apache::loncommon::start_data_table_header_row().
                   10719:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10720:0):                  &Apache::loncommon::end_data_table_header_row().
                   10721:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10722: # Get correct result
                   10723: # FIXME: Possibly need delimiter other than ":"
                   10724:     my @correct=();
1.415     www      10725:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10726:     my $number=$env{'form.number'};
                   10727:     if ($gradingmechanism ne 'attendance') {
1.414     www      10728:        foreach my $key (keys(%env)) {
                   10729:           if ($key=~/^form\.correct\:/) {
                   10730:              my @input=split(/\,/,$env{$key});
                   10731:              for (my $i=0;$i<=$#input;$i++) {
                   10732:                  if (($correct[$i]) && ($input[$i]) &&
                   10733:                      ($correct[$i] ne $input[$i])) {
                   10734:                     $result.='<br /><span class="LC_warning">'.
                   10735:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10736:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10737:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10738:                     $correct[$i]=$input[$i];
                   10739:                  }
                   10740:              }
                   10741:           }
                   10742:        }
1.415     www      10743:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10744:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10745:              $result.='<br /><span class="LC_error">'.
                   10746:                       &mt('No correct result given for question "[_1]"!',
                   10747:                           $env{'form.question:'.$i}).'</span>';
                   10748:           }
                   10749:        }
1.596.2.4  raeburn  10750:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10751:     }
                   10752: # Start grading
1.415     www      10753:     my $pcorrect=$env{'form.pcorrect'};
                   10754:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10755:     my $storecount=0;
1.596.2.4  raeburn  10756:     my %users=();
1.415     www      10757:     foreach my $key (keys(%env)) {
1.420     www      10758:        my $user='';
1.415     www      10759:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10760:           $user=$1;
                   10761:        }
                   10762:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10763:           my $id=$1;
                   10764:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10765:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10766:           } elsif ($env{'form.multi'.$id}) {
                   10767:              $user=$env{'form.multi'.$id};
1.420     www      10768:           }
                   10769:        }
1.596.2.4  raeburn  10770:        if ($user) {
                   10771:           if ($users{$user}) {
                   10772:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10773:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10774:                       '</span><br />';
                   10775:           }
                   10776:           $users{$user}=1;
1.415     www      10777:           my @answer=split(/\,/,$env{$key});
                   10778:           my $sum=0;
1.522     www      10779:           my $realnumber=$number;
1.415     www      10780:           for (my $i=0;$i<$number;$i++) {
1.576     www      10781:              if  ($correct[$i] eq '-') {
                   10782:                 $realnumber--;
1.596.2.12.2.  1(raebur 10783:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      10784:                 if ($gradingmechanism eq 'attendance') {
                   10785:                    $sum+=$pcorrect;
1.576     www      10786:                 } elsif ($correct[$i] eq '*') {
1.522     www      10787:                    $sum+=$pcorrect;
1.415     www      10788:                 } else {
1.596.2.4  raeburn  10789: # We actually grade if correct or not
                   10790:                    my $increment=$pincorrect;
                   10791: # Special case: numerical answer "0"
                   10792:                    if ($correct[$i] eq '0') {
                   10793:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10794:                          $increment=$pcorrect;
                   10795:                       }
                   10796: # General numerical answer, both evaluate to something non-zero
                   10797:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10798:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10799:                          $increment=$pcorrect;
                   10800:                       }
                   10801: # Must be just alphanumeric
                   10802:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10803:                       $increment=$pcorrect;
1.415     www      10804:                    }
1.596.2.4  raeburn  10805:                    $sum+=$increment;
1.415     www      10806:                 }
                   10807:              }
                   10808:           }
1.522     www      10809:           my $ave=$sum/(100*$realnumber);
1.416     www      10810: # Store
                   10811:           my ($username,$domain)=split(/\:/,$user);
                   10812:           my %grades=();
                   10813:           $grades{"resource.$part.solved"}='correct_by_override';
                   10814:           $grades{"resource.$part.awarded"}=$ave;
                   10815:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10816:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10817:                                                  $env{'request.course.id'},
                   10818:                                                  $domain,$username);
                   10819:           if ($returncode ne 'ok') {
                   10820:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10821:           } else {
                   10822:              $storecount++;
                   10823:           }
1.415     www      10824:        }
                   10825:     }
                   10826: # We are done
1.549     hauer    10827:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10828:              '</td>'.
                   10829:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 10830:0):              &Apache::loncommon::end_data_table();
                   10831:0):     return $result;
1.414     www      10832: }
                   10833: 
1.582     raeburn  10834: sub navmap_errormsg {
                   10835:     return '<div class="LC_error">'.
                   10836:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10837:            &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  10838:            '</div>';
                   10839: }
                   10840: 
1.596.2.12.2.  (raeburn 10841:): sub startpage {
          5(raebur 10842:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 10843:9):     my %args;
                   10844:9):     if ($onload) {
                   10845:9):          my %loaditems = (
                   10846:9):                         'onload' => $onload,
                   10847:9):                       );
                   10848:9):          $args{'add_entries'} = \%loaditems;
                   10849:9):     }
          (raeburn 10850:):     if ($nomenu) {
          9(raebur 10851:9):         $args{'only_body'} = 1;
          5(raebur 10852:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 10853:):     } else {
          1(raebur 10854:0):         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
          9(raebur 10855:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 10856:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 10857:):     }
                   10858:):     unless ($nodisplayflag) {
          1(raebur 10859:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 10860:):     }
                   10861:): }
                   10862:): 
          1(raebur 10863:0): sub select_problem {
                   10864:0):     my ($r)=@_;
                   10865:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   10866:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   10867:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10868:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10869:0): }
                   10870:0): 
1.1       albertel 10871: sub handler {
1.41      ng       10872:     my $request=$_[0];
1.434     albertel 10873:     &reset_caches();
1.596.2.4  raeburn  10874:     if ($request->header_only) {
                   10875:         &Apache::loncommon::content_type($request,'text/html');
                   10876:         $request->send_http_header;
                   10877:         return OK;
1.41      ng       10878:     }
                   10879:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10880: 
1.596.2.12.2.  1(raebur 10881:0): # see what command we need to execute
                   10882:0):  
1.160     albertel 10883:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10884:     my $command=$commands[0];
1.447     foxr     10885: 
1.596.2.12.2.  1(raebur 10886:0):     &init_perm();
                   10887:0):     if (!$env{'request.course.id'}) {
                   10888:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10889:0):                 ($command =~ /^scantronupload/)) {
                   10890:0):             # Not in a course.
                   10891:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10892:0):             return HTTP_NOT_ACCEPTABLE;
                   10893:0):         }
                   10894:0):     } elsif (!%perm) {
                   10895:0):         $request->internal_redirect('/adm/quickgrades');
                   10896:0):         return OK;
                   10897:0):     }
                   10898:0):     &Apache::loncommon::content_type($request,'text/html');
                   10899:0):     $request->send_http_header;
                   10900:0): 
1.160     albertel 10901:     if ($#commands > 0) {
                   10902: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10903:     }
1.447     foxr     10904: 
1.596.2.12.2.  1(raebur 10905:0): # see what the symb is
                   10906:0): 
                   10907:0):     my $symb=$env{'form.symb'};
                   10908:0):     unless ($symb) {
                   10909:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10910:0):        $symb=&Apache::lonnet::symbread($url);
                   10911:0):     }
                   10912:0):     &Apache::lonenc::check_decrypt(\$symb);
                   10913:0): 
1.513     foxr     10914:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 10915:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   10916:0): #
                   10917:0): # Not called from a resource, but inside a course
                   10918:0): #
                   10919:0):         &startpage($request,undef,[],1,1);
                   10920:0):         &select_problem($request);
1.41      ng       10921:     } else {
1.596.2.12.2.  1(raebur 10922:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   10923:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 10924:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10925:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10926:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10927:):                                               $env{'form.userdom'});
                   10928:):             }
          1(raebur 10929:0):             my $divforres;
                   10930:0):             if ($env{'form.student'} eq '') {
                   10931:0):                 $js .= &part_selector_js();
                   10932:0):                 $onload = "toggleParts('gradesub');";
                   10933:0):             } else {
                   10934:0):                 $divforres = 1;
                   10935:0):             }
          5(raebur 10936:0):             my $head_extra = $js;
                   10937:0):             unless ($env{'form.vProb'} eq 'no') {
                   10938:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   10939:0):                 if ($csslinks) {
                   10940:0):                     $head_extra .= "\n$csslinks";
                   10941:0):                 }
                   10942:0):             }
                   10943:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   10944:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 10945:):             if ($versionform) {
          2(raebur 10946:0):                 if ($divforres) {
                   10947:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   10948:0):                 }
          (raeburn 10949:):                 $request->print($versionform);
                   10950:):             }
          1(raebur 10951:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 10952:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10953:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10954:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10955:):                                           $env{'form.userdom'},
                   10956:):                                           $env{'form.inhibitmenu'});
          5(raebur 10957:0):             my $head_extra = $js;
                   10958:0):             unless ($env{'form.vProb'} eq 'no') {
                   10959:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   10960:0):                 if ($csslinks) {
                   10961:0):                     $head_extra .= "\n$csslinks";
                   10962:0):                 }
                   10963:0):             }
                   10964:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   10965:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 10966:):             if ($versionform) {
                   10967:):                 $request->print($versionform);
                   10968:):             }
                   10969:):             $request->print('<br clear="all" />');
                   10970:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 10971:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   10972:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10973:0):                                        {href=>'',text=>'Select student'}],1,1);
                   10974:0):             &pickStudentPage($request,$symb);
                   10975:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 10976:0):             my $csslinks;
                   10977:0):             unless ($env{'form.vProb'} eq 'no') {
                   10978:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   10979:0):             }
          1(raebur 10980:0):             &startpage($request,$symb,
                   10981:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10982:0):                                        {href=>'',text=>'Select student'},
          5(raebur 10983:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 10984:0):             &displayPage($request,$symb);
                   10985:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   10986:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10987:0):                                        {href=>'',text=>'Select student'},
                   10988:0):                                        {href=>'',text=>'Grade student'},
                   10989:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   10990:0):             &updateGradeByPage($request,$symb);
                   10991:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 10992:0):             my $csslinks;
                   10993:0):             unless ($env{'form.vProb'} eq 'no') {
                   10994:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   10995:0):             }
          1(raebur 10996:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 10997:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 10998:0):             &processGroup($request,$symb);
                   10999:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11000:0):             &startpage($request,$symb);
                   11001:0):             $request->print(&grading_menu($request,$symb));
                   11002:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11003:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11004:0):             $request->print(&submit_options($request,$symb));
                   11005:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11006:0):             my $js = &part_selector_js();
                   11007:0):             my $onload = "toggleParts('gradesub');";
                   11008:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11009:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11010:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11011:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11012:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11013:0):             $request->print(&submit_options_table($request,$symb));
                   11014:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11015:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11016:0):             $request->print(&submit_options_sequence($request,$symb));
                   11017:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11018:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11019:0):             $request->print(&viewgrades($request,$symb));
                   11020:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11021:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11022:0):                                        {href=>'',text=>'Store grades'}]);
                   11023:0):             $request->print(&processHandGrade($request,$symb));
                   11024:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11025:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11026:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11027:0):                                                                              text=>"Modify grades"},
                   11028:0):                                        {href=>'', text=>"Store grades"}]);
                   11029:0):             $request->print(&editgrades($request,$symb));
                   11030:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11031:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11032:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11033:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11034:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11035:0):                                        {href=>'',text=>'Verification Result'}]);
                   11036:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11037:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11038:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11039:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11040:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11041:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11042:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11043:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11044:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11045:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11046:0):                                        {href=>'', text=>'Process clicker file'},
                   11047:0):                                        {href=>'', text=>'Store grades'}]);
                   11048:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11049:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11050:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11051:0):             $request->print(&upcsvScores_form($request,$symb));
                   11052:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11053:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11054:0):             $request->print(&csvupload($request,$symb));
                   11055:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11056:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11057:0):             $request->print(&csvuploadmap($request,$symb));
                   11058:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11059:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11060:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11061:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11062:0):             } else {
                   11063:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11064:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11065:0):                 } else {
                   11066:0):                     $env{'form.upfile_associate'} = 'forward';
                   11067:0):                 }
                   11068:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11069:0):                 $request->print(&csvuploadmap($request,$symb));
                   11070:0):             }
                   11071:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11072:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11073:0):             $request->print(&csvuploadassign($request,$symb));
                   11074:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11075:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11076:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11077:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11078:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11079:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11080:0):             $request->print(&scantron_do_warning($request,$symb));
                   11081:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11082:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11083:0):             $request->print(&scantron_validate_file($request,$symb));
                   11084:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11085:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11086:0):             $request->print(&scantron_process_students($request,$symb));
                   11087:0):         } elsif ($command eq 'scantronupload' &&
                   11088:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11089:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11090:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11091:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11092:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11093:0):         } elsif ($command eq 'scantronupload_save' &&
                   11094:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11095:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11096:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11097:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11098:0):         } elsif ($command eq 'scantron_download' &&
                   11099:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11100:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11101:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11102:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11103:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11104:0):             $request->print(&checkscantron_results($request,$symb));
                   11105:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11106:0):             my $js = &part_selector_js();
                   11107:0):             my $onload = "toggleParts('gradingMenu');";
                   11108:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11109:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11110:0):             $request->print(&submit_options_download($request,$symb));
                   11111:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11112:0):             &startpage($request,$symb,
                   11113:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11114:0):     {href=>'', text=>'Download submitted files'}],
                   11115:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11116:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11117:0):             &submit_download_link($request,$symb);
                   11118:0):         } elsif ($command) {
                   11119:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11120:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11121:0):         }
1.2       albertel 11122:     }
1.513     foxr     11123:     if ($ssi_error) {
                   11124: 	&ssi_print_error($request);
                   11125:     }
1.353     albertel 11126:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11127:     &reset_caches();
1.596.2.4  raeburn  11128:     return OK;
1.44      ng       11129: }
                   11130: 
1.1       albertel 11131: 1;
                   11132: 
1.13      albertel 11133: __END__;
1.531     jms      11134: 
                   11135: 
                   11136: =head1 NAME
                   11137: 
                   11138: Apache::grades
                   11139: 
                   11140: =head1 SYNOPSIS
                   11141: 
                   11142: Handles the viewing of grades.
                   11143: 
                   11144: This is part of the LearningOnline Network with CAPA project
                   11145: described at http://www.lon-capa.org.
                   11146: 
                   11147: =head1 OVERVIEW
                   11148: 
                   11149: Do an ssi with retries:
                   11150: While I'd love to factor out this with the vesrion in lonprintout,
                   11151: 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
                   11152: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11153: 
                   11154: At least the logic that drives this has been pulled out into loncommon.
                   11155: 
                   11156: 
                   11157: 
                   11158: ssi_with_retries - Does the server side include of a resource.
                   11159:                      if the ssi call returns an error we'll retry it up to
                   11160:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11161:4):                      If we still have a problem, no text is appended to the
1.531     jms      11162:                      output and we set some global variables.
                   11163:                      to indicate to the caller an SSI error occurred.  
                   11164:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11165:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11166:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11167:                      by informing the user that this happened.
                   11168: 
                   11169: Parameters:
                   11170:   resource   - The resource to include.  This is passed directly, without
                   11171:                interpretation to lonnet::ssi.
                   11172:   form       - The form hash parameters that guide the interpretation of the resource
                   11173:                
                   11174:   retries    - Number of retries allowed before giving up completely.
                   11175: Returns:
                   11176:   On success, returns the rendered resource identified by the resource parameter.
                   11177: Side Effects:
                   11178:   The following global variables can be set:
                   11179:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11180:                               It is up to the caller to initialize this to false
                   11181:                               if desired.
                   11182:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11183:                               of the resource that could not be rendered by the ssi
                   11184:                               call.
                   11185:    ssi_error_message   - The error string fetched from the ssi response
                   11186:                               in the event of an error.
                   11187: 
                   11188: 
                   11189: =head1 HANDLER SUBROUTINE
                   11190: 
                   11191: ssi_with_retries()
                   11192: 
                   11193: =head1 SUBROUTINES
                   11194: 
                   11195: =over
                   11196: 
                   11197: =item scantron_get_correction() : 
                   11198: 
                   11199:    Builds the interface screen to interact with the operator to fix a
                   11200:    specific error condition in a specific scanline
                   11201: 
                   11202:  Arguments:
                   11203:     $r           - Apache request object
                   11204:     $i           - number of the current scanline
                   11205:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11206:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11207:     $line        - full contents of the current scanline
                   11208:     $error       - error condition, valid values are
                   11209:                    'incorrectCODE', 'duplicateCODE',
                   11210:                    'doublebubble', 'missingbubble',
                   11211:                    'duplicateID', 'incorrectID'
                   11212:     $arg         - extra information needed
                   11213:        For errors:
                   11214:          - duplicateID   - paper number that this studentID was seen before on
                   11215:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11216:                            seen on before
                   11217:          - incorrectCODE - current incorrect CODE 
                   11218:          - doublebubble  - array ref of the bubble lines that have double
                   11219:                            bubble errors
                   11220:          - missingbubble - array ref of the bubble lines that have missing
                   11221:                            bubble errors
                   11222: 
1.596.2.12.2.  6(raebur 11223:3):    $randomorder - True if exam folder has randomorder set
                   11224:3):    $randompick  - True if exam folder has randompick set
                   11225:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11226:3):                      for current line to question number used for same question
                   11227:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11228:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11229:3):                   and value is number of first bubble line for current student
                   11230:3):                   or code-based randompick and/or randomorder.
                   11231:3): 
                   11232:3): 
1.531     jms      11233: =item  scantron_get_maxbubble() : 
                   11234: 
1.582     raeburn  11235:    Arguments:
                   11236:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11237:                       failure to retrieve a navmap object.
                   11238:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11239:        calling routine should trap the error condition and display the warning
                   11240:        found in &navmap_errormsg().
                   11241: 
1.596.2.12.2.  (raeburn 11242:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11243:): 
1.531     jms      11244:    Returns the maximum number of bubble lines that are expected to
                   11245:    occur. Does this by walking the selected sequence rendering the
                   11246:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11247:    for what the current value of the problem counter is.
                   11248: 
                   11249:    Caches the results to $env{'form.scantron_maxbubble'},
                   11250:    $env{'form.scantron.bubble_lines.n'}, 
                   11251:    $env{'form.scantron.first_bubble_line.n'} and
                   11252:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11253:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11254:    lines for response n and number of the first bubble line for response n,
                   11255:    and a comma separated list of numbers of bubble lines for sub-questions
                   11256:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11257: 
                   11258: 
                   11259: =item  scantron_validate_missingbubbles() : 
                   11260: 
                   11261:    Validates all scanlines in the selected file to not have any
                   11262:     answers that don't have bubbles that have not been verified
                   11263:     to be bubble free.
                   11264: 
                   11265: =item  scantron_process_students() : 
                   11266: 
1.596.2.6  raeburn  11267:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11268: 
                   11269:    The parsed scanline hash is added to %env 
                   11270: 
                   11271:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11272:    foreach resource , with the form data of
                   11273: 
                   11274: 	'submitted'     =>'scantron' 
                   11275: 	'grade_target'  =>'grade',
                   11276: 	'grade_username'=> username of student
                   11277: 	'grade_domain'  => domain of student
                   11278: 	'grade_courseid'=> of course
                   11279: 	'grade_symb'    => symb of resource to grade
                   11280: 
                   11281:     This triggers a grading pass. The problem grading code takes care
                   11282:     of converting the bubbled letter information (now in %env) into a
                   11283:     valid submission.
                   11284: 
                   11285: =item  scantron_upload_scantron_data() :
                   11286: 
1.596.2.6  raeburn  11287:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11288: 
                   11289: =item  scantron_upload_scantron_data_save() : 
                   11290: 
                   11291:    Adds a provided bubble information data file to the course if user
                   11292:    has the correct privileges to do so. 
                   11293: 
                   11294: =item  valid_file() :
                   11295: 
                   11296:    Validates that the requested bubble data file exists in the course.
                   11297: 
                   11298: =item  scantron_download_scantron_data() : 
                   11299: 
                   11300:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11301:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11302:    course.
                   11303: 
                   11304: =item  scantron_validate_ID() : 
                   11305: 
                   11306:    Validates all scanlines in the selected file to not have any
1.556     weissno  11307:    invalid or underspecified student/employee IDs
1.531     jms      11308: 
1.582     raeburn  11309: =item navmap_errormsg() :
                   11310: 
                   11311:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11312:    Should be called whenever the request to instantiate a navmap object fails.  
                   11313: 
1.531     jms      11314: =back
                   11315: 
                   11316: =cut

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