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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.596.2.12.2.  0(raebur    4:2): # $Id: grades.pm,v 1.596.2.12.2.59 2021/12/17 20:20:14 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.596.2.4  raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.596.2.12.2.  1(raebur   46:0): use Apache::lonstathelpers;
1.596.2.4  raeburn    47: use Apache::bridgetask();
1.596.2.12.2.  4(raebur   48:8): use Apache::lontexconvert();
          7(raebur   49:9): use HTML::Parser();
                     50:9): use File::MMagic;
1.170     albertel   51: use String::Similarity;
1.359     www        52: use LONCAPA;
                     53: 
1.315     bowersj2   54: use POSIX qw(floor);
1.87      www        55: 
1.435     foxr       56: 
1.513     foxr       57: 
1.435     foxr       58: my %perm=();
1.596.2.12.2.  (raeburn   59:): my %old_essays=();
1.447     foxr       60: 
1.513     foxr       61: #  These variables are used to recover from ssi errors
                     62: 
                     63: my $ssi_retries = 5;
                     64: my $ssi_error;
                     65: my $ssi_error_resource;
                     66: my $ssi_error_message;
                     67: 
                     68: 
                     69: sub ssi_with_retries {
                     70:     my ($resource, $retries, %form) = @_;
                     71:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     72:     if ($response->is_error) {
                     73: 	$ssi_error          = 1;
                     74: 	$ssi_error_resource = $resource;
                     75: 	$ssi_error_message  = $response->code . " " . $response->message;
                     76:     }
                     77: 
                     78:     return $content;
                     79: 
                     80: }
                     81: #
                     82: #  Prodcuces an ssi retry failure error message to the user:
                     83: #
                     84: 
                     85: sub ssi_print_error {
                     86:     my ($r) = @_;
1.516     raeburn    87:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     88:     $r->print('
                     89: <br />
                     90: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     91: <p>
                     92: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     93: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     94: '.&mt('Error:').' '.$ssi_error_message.'
                     95: </p>
                     96: <p>'.
                     97: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     98: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     99: '</p>');
                    100:     return;
1.513     foxr      101: }
                    102: 
1.44      ng        103: #
1.146     albertel  104: # --- Retrieve the parts from the metadata file.---
1.596.2.12.2.  1(raebur  105:0): # Returns an array of everything that the resources stores away
                    106:0): #
                    107:0): 
1.44      ng        108: sub getpartlist {
1.582     raeburn   109:     my ($symb,$errorref) = @_;
1.439     albertel  110: 
                    111:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   112:     unless (ref($navmap)) {
                    113:         if (ref($errorref)) { 
                    114:             $$errorref = 'navmap';
                    115:             return;
                    116:         }
                    117:     }
1.439     albertel  118:     my $res      = $navmap->getBySymb($symb);
                    119:     my $partlist = $res->parts();
                    120:     my $url      = $res->src();
                    121:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    122: 
1.146     albertel  123:     my @stores;
1.439     albertel  124:     foreach my $part (@{ $partlist }) {
1.146     albertel  125: 	foreach my $key (@metakeys) {
                    126: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    127: 	}
                    128:     }
                    129:     return @stores;
1.2       albertel  130: }
                    131: 
1.129     ng        132: #--- Format fullname, username:domain if different for display
                    133: #--- Use anywhere where the student names are listed
                    134: sub nameUserString {
                    135:     my ($type,$fullname,$uname,$udom) = @_;
                    136:     if ($type eq 'header') {
1.485     albertel  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        138:     } else {
1.398     albertel  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        141:     }
                    142: }
                    143: 
1.44      ng        144: #--- Get the partlist and the response type for a given problem. ---
                    145: #--- Indicate if a response type is coded handgraded or not. ---
1.596.2.12.2.  1(raebur  146:0): #--- Count responseIDs, essayresponse items, and dropbox items ---
                    147:0): #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        148: sub response_type {
1.582     raeburn   149:     my ($symb,$response_error) = @_;
1.377     albertel  150: 
                    151:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   152:     unless (ref($navmap)) {
                    153:         if (ref($response_error)) {
                    154:             $$response_error = 1;
                    155:         }
                    156:         return;
                    157:     }
1.377     albertel  158:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   159:     unless (ref($res)) {
                    160:         $$response_error = 1;
                    161:         return;
                    162:     }
1.377     albertel  163:     my $partlist = $res->parts();
1.596.2.12.2.  1(raebur  164:0):     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  165:     my %vPart = 
                    166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  167:     my (%response_types,%handgrade);
                    168:     foreach my $part (@{ $partlist }) {
1.392     albertel  169: 	next if (%vPart && !exists($vPart{$part}));
                    170: 
1.377     albertel  171: 	my @types = $res->responseType($part);
                    172: 	my @ids = $res->responseIds($part);
                    173: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.596.2.12.2.  1(raebur  174:0):             $numresp ++;
1.377     albertel  175: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.596.2.12.2.  1(raebur  176:0):             if ($types[$i] eq 'essay') {
                    177:0):                 $numessay ++;
                    178:0):                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
                    179:0):                     $numdropbox ++;
                    180:0):                 }
                    181:0):             }
1.377     albertel  182: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    183: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    184: 				     '.handgrade',$symb);
1.41      ng        185: 	}
                    186:     }
1.596.2.12.2.  1(raebur  187:0):     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        188: }
                    189: 
1.375     albertel  190: sub flatten_responseType {
                    191:     my ($responseType) = @_;
                    192:     my @part_response_id =
                    193: 	map { 
                    194: 	    my $part = $_;
                    195: 	    map {
                    196: 		[$part,$_]
                    197: 		} sort(keys(%{ $responseType->{$part} }));
                    198: 	} sort(keys(%$responseType));
                    199:     return @part_response_id;
                    200: }
                    201: 
1.207     albertel  202: sub get_display_part {
1.324     albertel  203:     my ($partID,$symb)=@_;
1.207     albertel  204:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    205:     if (defined($display) and $display ne '') {
1.577     bisitz    206:         $display.= ' (<span class="LC_internal_info">'
                    207:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  208:     } else {
                    209: 	$display=$partID;
                    210:     }
                    211:     return $display;
                    212: }
1.269     raeburn   213: 
1.596.2.12.2.  1(raebur  214:0): #--- Show parts and response type
1.118     ng        215: sub showResourceInfo {
1.596.2.12.2.  1(raebur  216:0):     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
                    217:0):     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
                    218:0):         return '<br clear="all">';
                    219:0):     }
                    220:0):     my $coltitle = &mt('Problem Part Shown');
                    221:0):     if ($checkboxes) {
                    222:0):         $coltitle = &mt('Problem Part');
                    223:0):     } else {
                    224:0):         my $checkedparts = 0;
                    225:0):         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                    226:0):             if (grep(/^\Q$partid\E$/,@{$partlist})) {
                    227:0):                 $checkedparts ++;
                    228:0):             }
                    229:0):         }
                    230:0):         if ($checkedparts == scalar(@{$partlist})) {
                    231:0):             return '<br clear="all">';
                    232:0):         }
                    233:0):         if ($uploads) {
                    234:0):             $coltitle = &mt('Problem Part Selected');
1.582     raeburn   235:         }
                    236:     }
1.596.2.12.2.  1(raebur  237:0):     my $result = '<div class="LC_left_float" style="display:inline-block;">';
1.584     bisitz    238:     if ($checkboxes) {
1.596.2.12.2.  1(raebur  239:0):         my $legend = &mt('Parts to display');
                    240:0):         if ($uploads) {
                    241:0):             $legend = &mt('Part(s) with dropbox');
                    242:0):         }
                    243:0):         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
                    244:0):                    '<span class="LC_nobreak">'.
                    245:0):                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
                    246:0):                    &mt('All parts').'</label>'.('&nbsp;'x2).
                    247:0):                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
                    248:0):                    &mt('Selected parts').'</label></span>'.
                    249:0):                    '<div id="LC_partselector" style="display:none">';
1.584     bisitz    250:     }
1.596.2.12.2.  1(raebur  251:0):     $result .= &Apache::loncommon::start_data_table()
                    252:0):               .&Apache::loncommon::start_data_table_header_row();
                    253:0):     if ($checkboxes) {
                    254:0):         $result .= '<th>'.&mt('Display?').'</th>';
                    255:0):     }
                    256:0):     $result .= '<th>'.$coltitle.'</th>'
                    257:0):               .'<th>'.&mt('Res. ID').'</th>'
                    258:0):               .'<th>'.&mt('Type').'</th>'
                    259:0):               .&Apache::loncommon::end_data_table_header_row();
1.154     albertel  260:     my %partsseen;
1.524     raeburn   261:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    262:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    263:             my $responsetype = $responseType->{$partID}->{$resID};
1.596.2.12.2.  1(raebur  264:0):             if ($uploads) {
                    265:0):                 next unless ($responsetype eq 'essay');
                    266:0):                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
                    267:0):             }
                    268:0):             my $display_part=&get_display_part($partID,$symb);
                    269:0):             if (exists($partsseen{$partID})) {
                    270:0):                 $result.=&Apache::loncommon::continue_data_table_row();
                    271:0):             } else {
                    272:0):                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
                    273:0):                 $result.=&Apache::loncommon::start_data_table_row().
                    274:0):                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
                    275:0):                 if ($checkboxes) {
                    276:0):                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
                    277:0):                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
1.584     bisitz    278:                 } else {
1.596.2.12.2.  1(raebur  279:0):                     $result.=$display_part.'</td>';
1.584     bisitz    280:                 }
                    281:             }
1.596.2.12.2.  1(raebur  282:0):             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
1.584     bisitz    283:                     .'<td>'.&mt($responsetype).'</td>'
                    284:                     .&Apache::loncommon::end_data_table_row();
                    285:         }
1.118     ng        286:     }
1.584     bisitz    287:     $result.=&Apache::loncommon::end_data_table();
1.596.2.12.2.  1(raebur  288:0):     if ($checkboxes) {
                    289:0):         $result .= '</div></fieldset>';
                    290:0):     }
                    291:0):     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
          2(raebur  292:0):     if (!keys(%partsseen)) {
                    293:0):         $result = '';
                    294:0):         if ($uploads) {
                    295:0):             return '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
                    296:0):                    '<p class="LC_info">'.
                    297:0):                     &mt('No dropbox items or essayresponse items with uploadedfiletypes set.').
                    298:0):                    '</p>';
                    299:0):         } else {
                    300:0):             return '<br clear="all" />';
                    301:0):         }
                    302:0):     }  
          1(raebur  303:0):     return $result;
                    304:0): }
                    305:0): 
                    306:0): sub part_selector_js {
                    307:0):     my $js = <<"END";
                    308:0): function toggleParts(formname) {
                    309:0):     if (document.getElementById('LC_partselector')) {
                    310:0):         var index = '';
                    311:0):         if (document.forms.length) {
                    312:0):             for (var i=0; i<document.forms.length; i++) {
                    313:0):                 if (document.forms[i].name == formname) {
                    314:0):                     index = i;
                    315:0):                     break;
                    316:0):                 }
                    317:0):             }
                    318:0):         }
                    319:0):         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    320:0):             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    321:0):                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    322:0):                    var val = document.forms[index].elements['chooseparts'][i].value;
                    323:0):                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    324:0):                         document.getElementById('LC_partselector').style.display = 'block';
                    325:0):                     } else {
                    326:0):                         document.getElementById('LC_partselector').style.display = 'none';
                    327:0):                     }
                    328:0):                 }
                    329:0):             }
                    330:0):         }
                    331:0):     }
                    332:0): }
                    333:0): END
                    334:0):     return &Apache::lonhtmlcommon::scripttag($js);
1.118     ng        335: }
                    336: 
1.434     albertel  337: sub reset_caches {
                    338:     &reset_analyze_cache();
                    339:     &reset_perm();
1.596.2.12.2.  (raeburn  340:):     &reset_old_essays();
1.434     albertel  341: }
                    342: 
                    343: {
                    344:     my %analyze_cache;
1.557     raeburn   345:     my %analyze_cache_formkeys;
1.148     albertel  346: 
1.434     albertel  347:     sub reset_analyze_cache {
                    348: 	undef(%analyze_cache);
1.557     raeburn   349:         undef(%analyze_cache_formkeys);
1.434     albertel  350:     }
                    351: 
                    352:     sub get_analyze {
1.596.2.12.2.  (raeburn  353:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  354: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   355:         if ($type eq 'randomizetry') {
                    356:             if ($trial ne '') {
                    357:                 $key .= "\0".$trial;
                    358:             }
                    359:         }
1.557     raeburn   360: 	if (exists($analyze_cache{$key})) {
                    361:             my $getupdate = 0;
                    362:             if (ref($add_to_hash) eq 'HASH') {
                    363:                 foreach my $item (keys(%{$add_to_hash})) {
                    364:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    365:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    366:                             $getupdate = 1;
                    367:                             last;
                    368:                         }
                    369:                     } else {
                    370:                         $getupdate = 1;
                    371:                     }
                    372:                 }
                    373:             }
                    374:             if (!$getupdate) {
                    375:                 return $analyze_cache{$key};
                    376:             }
                    377:         }
1.434     albertel  378: 
                    379: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    380: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   381:         my %form = ('grade_target'      => 'analyze',
                    382:                     'grade_domain'      => $udom,
                    383:                     'grade_symb'        => $symb,
                    384:                     'grade_courseid'    =>  $env{'request.course.id'},
                    385:                     'grade_username'    => $uname,
                    386:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  387:):         if ($bubbles_per_row ne '') {
                    388:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    389:):         }
1.596.2.2  raeburn   390:         if ($type eq 'randomizetry') {
                    391:             $form{'grade_questiontype'} = $type;
                    392:             if ($rndseed ne '') {
                    393:                 $form{'grade_rndseed'} = $rndseed;
                    394:             }
                    395:         }
1.557     raeburn   396:         if (ref($add_to_hash)) {
                    397:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   398:         }
1.557     raeburn   399: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  400: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    401: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   402:         if (ref($add_to_hash) eq 'HASH') {
                    403:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    404:         } else {
                    405:             $analyze_cache_formkeys{$key} = {};
                    406:         }
1.434     albertel  407: 	return $analyze_cache{$key} = \%analyze;
                    408:     }
                    409: 
                    410:     sub get_order {
1.596.2.2  raeburn   411: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    412: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  413: 	return $analyze->{"$partid.$respid.shown"};
                    414:     }
                    415: 
                    416:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   417: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    418: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    419:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   420:         if (ref($foils) eq 'ARRAY') {
                    421: 	    foreach my $foil (@{$foils}) {
                    422: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    423: 		    return $foil;
                    424: 	        }
1.434     albertel  425: 	    }
                    426: 	}
                    427:     }
1.554     raeburn   428: 
                    429:     sub scantron_partids_tograde {
1.596.2.12.2.  1(raebur  430:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   431:         my (%analysis,@parts);
                    432:         if (ref($resource)) {
                    433:             my $symb = $resource->symb();
1.557     raeburn   434:             my $add_to_form;
                    435:             if ($check_for_randomlist) {
                    436:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    437:             }
1.596.2.12.2.  1(raebur  438:7):             if ($scancode) {
                    439:7):                 if (ref($add_to_form) eq 'HASH') {
                    440:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    441:7):                 } else {
                    442:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    443:7):                 }
                    444:7):             }
          (raeburn  445:):             my $analyze =
                    446:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    447:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   448:             if (ref($analyze) eq 'HASH') {
                    449:                 %analysis = %{$analyze};
                    450:             }
                    451:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    452:                 foreach my $part (@{$analysis{'parts'}}) {
                    453:                     my ($id,$respid) = split(/\./,$part);
                    454:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    455:                         push(@parts,$part);
                    456:                     }
                    457:                 }
                    458:             }
                    459:         }
                    460:         return (\%analysis,\@parts);
                    461:     }
                    462: 
1.148     albertel  463: }
1.434     albertel  464: 
1.118     ng        465: #--- Clean response type for display
1.335     albertel  466: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    467: #        response types only.
1.118     ng        468: sub cleanRecord {
1.336     albertel  469:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   470: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  471:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  472:     if ($response =~ /^(option|rank)$/) {
                    473: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  474:4):         my @answer = %answer;
                    475:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  476: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    477: 	my ($toprow,$bottomrow);
                    478: 	foreach my $foil (@$order) {
                    479: 	    if ($grading{$foil} == 1) {
                    480: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    481: 	    } else {
                    482: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    483: 	    }
1.398     albertel  484: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  485: 	}
                    486: 	return '<blockquote><table border="1">'.
1.466     albertel  487: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    488: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   489: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  490:     } elsif ($response eq 'match') {
                    491: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  492:4):         my @answer = %answer;
                    493:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  494: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    495: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    496: 	my ($toprow,$middlerow,$bottomrow);
                    497: 	foreach my $foil (@$order) {
                    498: 	    my $item=shift(@items);
                    499: 	    if ($grading{$foil} == 1) {
                    500: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  501: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  502: 	    } else {
                    503: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  504: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  505: 	    }
1.398     albertel  506: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        507: 	}
1.126     ng        508: 	return '<blockquote><table border="1">'.
1.466     albertel  509: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    510: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  511: 	    $middlerow.'</tr>'.
1.466     albertel  512: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   513: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  514:     } elsif ($response eq 'radiobutton') {
                    515: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  1(raebur  516:0):         my @answer = %answer;
                    517:0):         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  518: 	my ($toprow,$bottomrow);
1.434     albertel  519: 	my $correct = 
1.596.2.2  raeburn   520: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  521: 	foreach my $foil (@$order) {
1.148     albertel  522: 	    if (exists($answer{$foil})) {
1.434     albertel  523: 		if ($foil eq $correct) {
1.466     albertel  524: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  525: 		} else {
1.466     albertel  526: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  527: 		}
                    528: 	    } else {
1.466     albertel  529: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  530: 	    }
1.398     albertel  531: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  532: 	}
                    533: 	return '<blockquote><table border="1">'.
1.466     albertel  534: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    535: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   536: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  537:     } elsif ($response eq 'essay') {
1.257     albertel  538: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        539: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  540: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    541: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        542: 
1.257     albertel  543: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    544: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    545: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    546: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    547: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    548: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        549: 	}
1.596.2.12.2.  4(raebur  550:8):         $answer = &Apache::lontexconvert::msgtexconverted($answer);
          2(raebur  551:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  552:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  553:4):         my $result=&mt('Smile representation: [_1]',
                    554:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  555: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    556: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    557: 	return $result;
1.335     albertel  558:     } elsif ( $response eq 'Task') {
                    559: 	if ( $answer eq 'SUBMITTED') {
                    560: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  561: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  562: 	    return $result;
                    563: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    564: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    565: 			       keys(%{$record}));
                    566: 	    return join('<br />',($version,@matches));
                    567: 			       
                    568: 			       
                    569: 	} else {
                    570: 	    my $result =
                    571: 		'<p>'
                    572: 		.&mt('Overall result: [_1]',
                    573: 		     $record->{$version."resource.$respid.$partid.status"})
                    574: 		.'</p>';
                    575: 	    
                    576: 	    $result .= '<ul>';
                    577: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    578: 			     keys(%{$record}));
                    579: 	    foreach my $grade (sort(@grade)) {
                    580: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    581: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    582: 				     $dim, $record->{$grade}).
                    583: 			  '</li>';
                    584: 	    }
                    585: 	    $result.='</ul>';
                    586: 	    return $result;
                    587: 	}
1.596.2.12.2.  8(raebur  588:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    589:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  590: 	$answer = 
                    591: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    592: 							      $answer);
1.596.2.12.2.  1(raebur  593:0): 	return $answer;
1.122     ng        594:     }
1.596.2.12.2.  8(raebur  595:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        596: }
                    597: 
                    598: #-- A couple of common js functions
                    599: sub commonJSfunctions {
                    600:     my $request = shift;
1.596.2.12.2.  1(raebur  601:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        602:     function radioSelection(radioButton) {
                    603: 	var selection=null;
                    604: 	if (radioButton.length > 1) {
                    605: 	    for (var i=0; i<radioButton.length; i++) {
                    606: 		if (radioButton[i].checked) {
                    607: 		    return radioButton[i].value;
                    608: 		}
                    609: 	    }
                    610: 	} else {
                    611: 	    if (radioButton.checked) return radioButton.value;
                    612: 	}
                    613: 	return selection;
                    614:     }
                    615: 
                    616:     function pullDownSelection(selectOne) {
                    617: 	var selection="";
                    618: 	if (selectOne.length > 1) {
                    619: 	    for (var i=0; i<selectOne.length; i++) {
                    620: 		if (selectOne[i].selected) {
                    621: 		    return selectOne[i].value;
                    622: 		}
                    623: 	    }
                    624: 	} else {
1.138     albertel  625:             // only one value it must be the selected one
                    626: 	    return selectOne.value;
1.118     ng        627: 	}
                    628:     }
                    629: COMMONJSFUNCTIONS
                    630: }
                    631: 
1.44      ng        632: #--- Dumps the class list with usernames,list of sections,
                    633: #--- section, ids and fullnames for each user.
                    634: sub getclasslist {
1.596.2.12.2.  1(raebur  635:0):     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  636:     my @getsec;
1.450     banghart  637:     my @getgroup;
1.442     banghart  638:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  639:     if (!ref($getsec)) {
                    640: 	if ($getsec ne '' && $getsec ne 'all') {
                    641: 	    @getsec=($getsec);
                    642: 	}
                    643:     } else {
                    644: 	@getsec=@{$getsec};
                    645:     }
                    646:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  647:     if (!ref($getgroup)) {
                    648: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    649: 	    @getgroup=($getgroup);
                    650: 	}
                    651:     } else {
                    652: 	@getgroup=@{$getgroup};
                    653:     }
                    654:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  655: 
1.449     banghart  656:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  657:     # Bail out if we were unable to get the classlist
1.56      matthew   658:     return if (! defined($classlist));
1.449     banghart  659:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   660:     #
                    661:     my %sections;
                    662:     my %fullnames;
1.596.2.12.2.  1(raebur  663:0):     my ($cdom,$cnum,$partlist);
                    664:0):     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    665:0):         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    666:0):         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    667:0):         my $res_error;
                    668:0):         ($partlist) = &response_type($symb,\$res_error);
                    669:0):     }
1.205     matthew   670:     foreach my $student (keys(%$classlist)) {
                    671:         my $end      = 
                    672:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    673:         my $start    = 
                    674:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    675:         my $id       = 
                    676:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    677:         my $section  = 
                    678:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    679:         my $fullname = 
                    680:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    681:         my $status   = 
                    682:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  683:         my $group   = 
                    684:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        685: 	# filter students according to status selected
1.596.2.12.2.  1(raebur  686:0): 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  687: 	    if (!($stu_status =~ $status)) {
1.450     banghart  688: 		delete($classlist->{$student});
1.76      ng        689: 		next;
                    690: 	    }
                    691: 	}
1.450     banghart  692: 	# filter students according to groups selected
1.453     banghart  693: 	my @stu_groups = split(/,/,$group);
1.450     banghart  694: 	if (@getgroup) {
                    695: 	    my $exclude = 1;
1.454     banghart  696: 	    foreach my $grp (@getgroup) {
                    697: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  698: 	            if ($stu_group eq $grp) {
                    699: 	                $exclude = 0;
                    700:     	            } 
1.450     banghart  701: 	        }
1.453     banghart  702:     	        if (($grp eq 'none') && !$group) {
1.596.2.12.2.  1(raebur  703:0):         	    $exclude = 0;
1.453     banghart  704:         	}
1.450     banghart  705: 	    }
                    706: 	    if ($exclude) {
                    707: 	        delete($classlist->{$student});
1.596.2.12.2.  1(raebur  708:0): 		next;
1.450     banghart  709: 	    }
                    710: 	}
1.596.2.12.2.  1(raebur  711:0):         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    712:0):             my $udom =
                    713:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    714:0):             my $uname =
                    715:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    716:0):             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    717:0):                 if ($submitonly eq 'queued') {
                    718:0):                     my %queue_status =
                    719:0):                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    720:0):                                                                 $udom,$uname);
                    721:0):                     if (!defined($queue_status{'gradingqueue'})) {
                    722:0):                         delete($classlist->{$student});
                    723:0):                         next;
                    724:0):                     }
                    725:0):                 } else {
                    726:0):                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    727:0):                     my $submitted = 0;
                    728:0):                     my $graded = 0;
                    729:0):                     my $incorrect = 0;
                    730:0):                     foreach (keys(%status)) {
                    731:0):                         $submitted = 1 if ($status{$_} ne 'nothing');
                    732:0):                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    733:0):                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    734:0): 
                    735:0):                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    736:0):                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    737:0):                             $submitted = 0;
                    738:0):                         }
                    739:0):                     }
                    740:0):                     if (!$submitted && ($submitonly eq 'yes' ||
                    741:0):                                         $submitonly eq 'incorrect' ||
                    742:0):                                         $submitonly eq 'graded')) {
                    743:0):                         delete($classlist->{$student});
                    744:0):                         next;
                    745:0):                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    746:0):                         delete($classlist->{$student});
                    747:0):                         next;
                    748:0):                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    749:0):                         delete($classlist->{$student});
                    750:0):                         next;
                    751:0):                     }
                    752:0):                 }
                    753:0):             }
                    754:0):         }
1.205     matthew   755: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  756: 	if (&canview($section)) {
1.291     albertel  757: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  758: 		$sections{$section}++;
1.450     banghart  759: 		if ($classlist->{$student}) {
                    760: 		    $fullnames{$student}=$fullname;
                    761: 		}
1.103     albertel  762: 	    } else {
1.205     matthew   763: 		delete($classlist->{$student});
1.103     albertel  764: 	    }
                    765: 	} else {
1.205     matthew   766: 	    delete($classlist->{$student});
1.103     albertel  767: 	}
1.44      ng        768:     }
1.56      matthew   769:     my @sections = sort(keys(%sections));
                    770:     return ($classlist,\@sections,\%fullnames);
1.44      ng        771: }
                    772: 
1.103     albertel  773: sub canmodify {
                    774:     my ($sec)=@_;
                    775:     if ($perm{'mgr'}) {
                    776: 	if (!defined($perm{'mgr_section'})) {
                    777: 	    # can modify whole class
                    778: 	    return 1;
                    779: 	} else {
                    780: 	    if ($sec eq $perm{'mgr_section'}) {
                    781: 		#can modify the requested section
                    782: 		return 1;
                    783: 	    } else {
1.596.2.12.2.  1(raebur  784:0): 		# can't modify the requested section
1.103     albertel  785: 		return 0;
                    786: 	    }
                    787: 	}
                    788:     }
                    789:     #can't modify
                    790:     return 0;
                    791: }
                    792: 
                    793: sub canview {
                    794:     my ($sec)=@_;
                    795:     if ($perm{'vgr'}) {
                    796: 	if (!defined($perm{'vgr_section'})) {
1.596.2.12.2.  1(raebur  797:0): 	    # can view whole class
1.103     albertel  798: 	    return 1;
                    799: 	} else {
                    800: 	    if ($sec eq $perm{'vgr_section'}) {
1.596.2.12.2.  1(raebur  801:0): 		#can view the requested section
1.103     albertel  802: 		return 1;
                    803: 	    } else {
1.596.2.12.2.  1(raebur  804:0): 		# can't view the requested section
1.103     albertel  805: 		return 0;
                    806: 	    }
                    807: 	}
                    808:     }
1.596.2.12.2.  1(raebur  809:0):     #can't view
1.103     albertel  810:     return 0;
                    811: }
                    812: 
1.44      ng        813: #--- Retrieve the grade status of a student for all the parts
                    814: sub student_gradeStatus {
1.324     albertel  815:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  816:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        817:     my %partstatus = ();
                    818:     foreach (@$partlist) {
1.128     ng        819: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        820: 	$status              = 'nothing' if ($status eq '');
                    821: 	$partstatus{$_}      = $status;
                    822: 	my $subkey           = "resource.$_.submitted_by";
                    823: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    824:     }
                    825:     return %partstatus;
                    826: }
                    827: 
1.45      ng        828: # hidden form and javascript that calls the form
                    829: # Use by verifyscript and viewgrades
                    830: # Shows a student's view of problem and submission
                    831: sub jscriptNform {
1.324     albertel  832:     my ($symb) = @_;
1.442     banghart  833:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  1(raebur  834:0):     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        835: 	'    function viewOneStudent(user,domain) {'."\n".
                    836: 	'	document.onestudent.student.value = user;'."\n".
                    837: 	'	document.onestudent.userdom.value = domain;'."\n".
                    838: 	'	document.onestudent.submit();'."\n".
                    839: 	'    }'."\n".
1.596.2.12.2.  1(raebur  840:0): 	"\n");
1.45      ng        841:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  842: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  843: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        844: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    845: 	'<input type="hidden" name="student" value="" />'."\n".
                    846: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    847: 	'</form>'."\n";
                    848:     return $jscript;
                    849: }
1.39      ng        850: 
1.447     foxr      851: 
                    852: 
1.315     bowersj2  853: # Given the score (as a number [0-1] and the weight) what is the final
                    854: # point value? This function will round to the nearest tenth, third,
                    855: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  856: sub compute_points {
1.315     bowersj2  857:     my ($score, $weight) = @_;
                    858:     
                    859:     my $tolerance = .00001;
                    860:     my $points = $score * $weight;
                    861: 
                    862:     # Check for nearness to 1/x.
                    863:     my $check_for_nearness = sub {
                    864:         my ($factor) = @_;
                    865:         my $num = ($points * $factor) + $tolerance;
                    866:         my $floored_num = floor($num);
1.316     albertel  867:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  868:             return $floored_num / $factor;
                    869:         }
                    870:         return $points;
                    871:     };
                    872: 
                    873:     $points = $check_for_nearness->(10);
                    874:     $points = $check_for_nearness->(3);
                    875:     $points = $check_for_nearness->(4);
                    876:     
                    877:     return $points;
                    878: }
                    879: 
1.44      ng        880: #------------------ End of general use routines --------------------
1.87      www       881: 
                    882: #
                    883: # Find most similar essay
                    884: #
                    885: 
                    886: sub most_similar {
1.596.2.12.2.  (raeburn  887:):     my ($uname,$udom,$symb,$uessay)=@_;
                    888:): 
                    889:):     unless ($symb) { return ''; }
                    890:): 
                    891:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       892: 
                    893: # ignore spaces and punctuation
                    894: 
                    895:     $uessay=~s/\W+/ /gs;
                    896: 
1.282     www       897: # ignore empty submissions (occuring when only files are sent)
                    898: 
1.596.2.4  raeburn   899:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       900: 
1.87      www       901: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       902:     my $limit=0.6;
1.87      www       903:     my $sname='';
                    904:     my $sdom='';
                    905:     my $scrsid='';
                    906:     my $sessay='';
                    907: # go through all essays ...
1.596.2.12.2.  (raeburn  908:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  909: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       910: # ... except the same student
1.426     albertel  911:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  912:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  913: 	$tessay=~s/\W+/ /gs;
1.87      www       914: # String similarity gives up if not even limit
1.426     albertel  915: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       916: # Found one
1.426     albertel  917: 	if ($tsimilar>$limit) {
                    918: 	    $limit=$tsimilar;
                    919: 	    $sname=$tname;
                    920: 	    $sdom=$tdom;
                    921: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  922:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  923: 	}
1.87      www       924:     }
1.88      www       925:     if ($limit>0.6) {
1.87      www       926:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    927:     } else {
                    928:        return ('','','','',0);
                    929:     }
                    930: }
                    931: 
1.44      ng        932: #-------------------------------------------------------------------
                    933: 
                    934: #------------------------------------ Receipt Verification Routines
1.45      ng        935: #
1.596.2.12.2.  1(raebur  936:0): 
                    937:0): sub initialverifyreceipt {
                    938:0):    my ($request,$symb) = @_;
                    939:0):    &commonJSfunctions($request);
                    940:0):    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
                    941:0):         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    942:0):         '-<input type="text" name="receipt" size="4" />'.
                    943:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    944:0):         '<input type="hidden" name="command" value="verify" />'.
                    945:0):         "</form>\n";
                    946:0): }
                    947:0): 
1.44      ng        948: #--- Check whether a receipt number is valid.---
                    949: sub verifyreceipt {
1.596.2.12.2.  1(raebur  950:0):     my ($request,$symb) = @_;
1.44      ng        951: 
1.257     albertel  952:     my $courseid = $env{'request.course.id'};
1.184     www       953:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  954: 	$env{'form.receipt'};
1.44      ng        955:     $receipt     =~ s/[^\-\d]//g;
                    956: 
1.596.2.12.2.  1(raebur  957:0):     my $title =
1.487     albertel  958: 	'<h3><span class="LC_info">'.
1.596.2.12.2.  1(raebur  959:0): 	&mt('Verifying Receipt Number [_1]',$receipt).
                    960:0): 	'</span></h3>'."\n";
1.44      ng        961: 
                    962:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   963:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  964:     
                    965:     my $receiptparts=0;
1.390     albertel  966:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    967: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  968:     my $parts=['0'];
1.582     raeburn   969:     if ($receiptparts) {
                    970:         my $res_error; 
                    971:         ($parts)=&response_type($symb,\$res_error);
                    972:         if ($res_error) {
                    973:             return &navmap_errormsg();
                    974:         } 
                    975:     }
1.486     albertel  976:     
                    977:     my $header = 
                    978: 	&Apache::loncommon::start_data_table().
                    979: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  980: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    981: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    982: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  983:     if ($receiptparts) {
1.487     albertel  984: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  985:     }
                    986:     $header.=
                    987: 	&Apache::loncommon::end_data_table_header_row();
                    988: 
1.294     albertel  989:     foreach (sort 
                    990: 	     {
                    991: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    992: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    993: 		 }
                    994: 		 return $a cmp $b;
                    995: 	     } (keys(%$fullname))) {
1.44      ng        996: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  997: 	foreach my $part (@$parts) {
                    998: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  999: 		$contents.=
                   1000: 		    &Apache::loncommon::start_data_table_row().
                   1001: 		    '<td>&nbsp;'."\n".
1.177     albertel 1002: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 1003: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel 1004: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                   1005: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                   1006: 		if ($receiptparts) {
                   1007: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1008: 		}
1.486     albertel 1009: 		$contents.= 
                   1010: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1011: 		
                   1012: 		$matches++;
                   1013: 	    }
1.44      ng       1014: 	}
                   1015:     }
                   1016:     if ($matches == 0) {
1.584     bisitz   1017:         $string = $title
                   1018:                  .'<p class="LC_warning">'
                   1019:                  .&mt('No match found for the above receipt number.')
                   1020:                  .'</p>';
1.44      ng       1021:     } else {
1.324     albertel 1022: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1023: 	    '<p>'.
1.584     bisitz   1024: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1025: 	    '</p>'.
1.486     albertel 1026: 	    $header.
                   1027: 	    $contents.
                   1028: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1029:     }
1.596.2.12.2.  1(raebur 1030:0):     return $string;
1.44      ng       1031: }
                   1032: 
                   1033: #--- This is called by a number of programs.
                   1034: #--- Called from the Grading Menu - View/Grade an individual student
                   1035: #--- Also called directly when one clicks on the subm button 
                   1036: #    on the problem page.
1.30      ng       1037: sub listStudents {
1.596.2.12.2.  1(raebur 1038:0):     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1039: 
1.257     albertel 1040:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1041:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1042:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1043:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.596.2.12.2.  1(raebur 1044:0):     unless ($submitonly) {
                   1045:0):         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   1046:0):     }
                   1047:0): 
                   1048:0):     my $result='';
                   1049:0):     my $res_error;
                   1050:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
1.118     ng       1051: 
1.596.2.12.2.  1(raebur 1052:0):     my $table;
                   1053:0):     if (ref($partlist) eq 'ARRAY') {
                   1054:0):         if (scalar(@$partlist) > 1 ) {
                   1055:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1056:0):         } elsif ($divforres) {
                   1057:0):             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1058:0):         } else {
                   1059:0):             $table = '<br clear="all" />';
                   1060:0):         }
                   1061:0):     }
1.49      albertel 1062: 
1.596.2.12.2.  6(raebur 1063:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1064: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1065: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1066: 	     );
1.596.2.12.2.  6(raebur 1067:6):     &js_escape(\%js_lt);
          1(raebur 1068:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1069:     function checkSelect(checkBox) {
                   1070: 	var ctr=0;
                   1071: 	var sense="";
                   1072: 	if (checkBox.length > 1) {
                   1073: 	    for (var i=0; i<checkBox.length; i++) {
                   1074: 		if (checkBox[i].checked) {
                   1075: 		    ctr++;
                   1076: 		}
                   1077: 	    }
1.596.2.12.2.  6(raebur 1078:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng       1079: 	} else {
                   1080: 	    if (checkBox.checked) {
                   1081: 		ctr = 1;
                   1082: 	    }
1.596.2.12.2.  6(raebur 1083:6): 	    sense = '$js_lt{'single'}';
1.110     ng       1084: 	}
                   1085: 	if (ctr == 0) {
1.485     albertel 1086: 	    alert(sense);
1.110     ng       1087: 	    return false;
                   1088: 	}
                   1089: 	document.gradesub.submit();
                   1090:     }
                   1091: 
                   1092:     function reLoadList(formname) {
1.112     ng       1093: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1094: 	formname.command.value = 'submission';
                   1095: 	formname.submit();
                   1096:     }
1.45      ng       1097: LISTJAVASCRIPT
                   1098: 
1.118     ng       1099:     &commonJSfunctions($request);
1.41      ng       1100:     $request->print($result);
1.39      ng       1101: 
1.154     albertel 1102:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel 1103: 	"\n".$table;
1.596.2.12.2.  1(raebur 1104:0): 
1.561     bisitz   1105:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                   1106:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1107:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1108:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1109:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1110:                   .&Apache::lonhtmlcommon::row_closure();
                   1111:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1112:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1113:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1114:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1115:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1116: 
1.442     banghart 1117:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1118:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1119:     $env{'form.Status'} = $saveStatus;
1.596.2.12.2.  1(raebur 1120:0):     my %optiontext = &Apache::lonlocal::texthash (
                   1121:0):                           lastonly => 'last submission',
                   1122:0):                           last     => 'last submission with details',
                   1123:0):                           datesub  => 'all submissions',
                   1124:0):                           all      => 'all submissions with details',
                   1125:0):                       );
                   1126:0):     my $submission_options =
1.592     bisitz   1127:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1128:0):         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
                   1129:0):         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1130:         '<span class="LC_nobreak">'.
                   1131:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.596.2.12.2.  1(raebur 1132:0):         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1133:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1134:0):         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
                   1135:0):         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1136:         '<span class="LC_nobreak">'.
                   1137:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.596.2.12.2.  1(raebur 1138:0):         $optiontext{'all'}.'</label></span>';
                   1139:0):     my ($compmsg,$nocompmsg);
                   1140:0):     $nocompmsg = ' checked="checked"';
                   1141:0):     if ($numessay) {
                   1142:0):         $compmsg = $nocompmsg;
                   1143:0):         $nocompmsg = '';
                   1144:0):     }
1.561     bisitz   1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
1.596.2.12.2.  6(raebur 1146:1):                   .$submission_options;
                   1147:1): # Check if any gradable
                   1148:1):     my $showmore;
                   1149:1):     if ($perm{'mgr'}) {
                   1150:1):         my @sections;
                   1151:1):         if ($env{'request.course.sec'} ne '') {
                   1152:1):             @sections = ($env{'request.course.sec'});
          7(raebur 1153:1):         } elsif ($env{'form.section'} eq '') {
                   1154:1):             @sections = ('all');
          6(raebur 1155:1):         } else {
                   1156:1):             @sections = &Apache::loncommon::get_env_multiple('form.section');
                   1157:1):         }
                   1158:1):         if (grep(/^all$/,@sections)) {
                   1159:1):             $showmore = 1;
                   1160:1):         } else {
                   1161:1):             foreach my $sec (@sections) {
                   1162:1):                 if (&canmodify($sec)) {
                   1163:1):                     $showmore = 1;
                   1164:1):                     last;
                   1165:1):                 }
                   1166:1):             }
                   1167:1):         }
                   1168:1):     }
                   1169:1): 
                   1170:1):     if ($showmore) {
                   1171:1):         $gradeTable .=
                   1172:1):                    &Apache::lonhtmlcommon::row_closure()
          1(raebur 1173:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1174:0):                   .'<span class="LC_nobreak">'
                   1175:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1176:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1177:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1178:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1179:                   .&Apache::lonhtmlcommon::row_closure();
                   1180: 
1.596.2.12.2.  6(raebur 1181:1):         $gradeTable .= 
                   1182:1):                    &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1.561     bisitz   1183:                   .'<select name="increment">'
                   1184:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1185:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1186:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1187:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1188:0):                   .'</select>';
          6(raebur 1189:1):     }
1.485     albertel 1190:     $gradeTable .= 
1.432     banghart 1191:         &build_section_inputs().
1.45      ng       1192: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1194: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1195:0):     if (exists($env{'form.Status'})) {
          7(raebur 1196:1): 	$gradeTable .= '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng       1197:     } else {
1.596.2.12.2.  1(raebur 1198:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1199:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1200:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1201:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1202:     }
1.596.2.12.2.  1(raebur 1203:0):     if ($numessay) {
                   1204:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1205:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1206:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1207:0):     }
                   1208:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1209:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1210: 
                   1211:     $gradeTable .= '<p>'
1.596.2.12.2.  1(raebur 1212:0):                   .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1.561     bisitz   1213:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1214:                   .'</p>';
1.249     albertel 1215: 
                   1216: # checkall buttons
                   1217:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1218:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1219:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1220:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1221:     $gradeTable.=&check_buttons();
1.450     banghart 1222:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1223:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1224: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1225:     my $loop = 0;
                   1226:     while ($loop < 2) {
1.485     albertel 1227: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1228: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1229:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1230: 	    foreach my $part (sort(@$partlist)) {
                   1231: 		my $display_part=
                   1232: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1233: 		$gradeTable.=
                   1234: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1235: 	    }
1.301     albertel 1236: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1237: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1238: 	}
                   1239: 	$loop++;
1.126     ng       1240: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1241:     }
1.474     albertel 1242:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1243: 
1.45      ng       1244:     my $ctr = 0;
1.294     albertel 1245:     foreach my $student (sort 
                   1246: 			 {
                   1247: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1248: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1249: 			     }
                   1250: 			     return $a cmp $b;
                   1251: 			 }
                   1252: 			 (keys(%$fullname))) {
1.41      ng       1253: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1254: 
1.110     ng       1255: 	my %status = ();
1.301     albertel 1256: 
                   1257: 	if ($submitonly eq 'queued') {
                   1258: 	    my %queue_status = 
                   1259: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1260: 							$udom,$uname);
                   1261: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1262: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1263: 	}
                   1264: 
1.596.2.12.2.  1(raebur 1265:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1266: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1267: 	    my $submitted = 0;
1.164     albertel 1268: 	    my $graded = 0;
1.248     albertel 1269: 	    my $incorrect = 0;
1.110     ng       1270: 	    foreach (keys(%status)) {
1.145     albertel 1271: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1272: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1273: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1274: 		
1.110     ng       1275: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1276: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1277: 		    $submitted = 0;
1.150     albertel 1278: 		    my ($part)=split(/\./,$partid);
1.110     ng       1279: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1280: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1281: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1282: 		}
1.41      ng       1283: 	    }
1.248     albertel 1284: 	    
1.156     albertel 1285: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1286: 				     $submitonly eq 'incorrect' ||
                   1287: 				     $submitonly eq 'graded'));
1.248     albertel 1288: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1289: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1290: 	}
1.34      ng       1291: 
1.45      ng       1292: 	$ctr++;
1.249     albertel 1293: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1294:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1295: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1296: 	    if ($ctr%2 ==1) {
                   1297: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1298: 	    }
1.126     ng       1299: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1300:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1301:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1302: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1303: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1304: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1305: 
1.596.2.12.2.  1(raebur 1306:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1307: 		foreach (sort(keys(%status))) {
1.485     albertel 1308: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1309: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1310: 		}
1.41      ng       1311: 	    }
1.126     ng       1312: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1313: 	    if ($ctr%2 ==0) {
                   1314: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1315: 	    }
1.41      ng       1316: 	}
                   1317:     }
1.110     ng       1318:     if ($ctr%2 ==1) {
1.126     ng       1319: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1320:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1321: 		foreach (@$partlist) {
                   1322: 		    $gradeTable.='<td>&nbsp;</td>';
                   1323: 		}
1.301     albertel 1324: 	    } elsif ($submitonly eq 'queued') {
                   1325: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1326: 	    }
1.474     albertel 1327: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1328:     }
                   1329: 
1.474     albertel 1330:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1331:         '<input type="button" '.
                   1332:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1333:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1334:     if ($ctr == 0) {
1.96      albertel 1335: 	my $num_students=(scalar(keys(%$fullname)));
                   1336: 	if ($num_students eq 0) {
1.485     albertel 1337: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1338: 	} else {
1.171     albertel 1339: 	    my $submissions='submissions';
                   1340: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1341: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1342: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1343: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1344:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1345: 		    $num_students).
                   1346: 		'</span><br />';
1.96      albertel 1347: 	}
1.46      ng       1348:     } elsif ($ctr == 1) {
1.474     albertel 1349: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1350:     }
                   1351:     $request->print($gradeTable);
1.44      ng       1352:     return '';
1.10      ng       1353: }
                   1354: 
1.44      ng       1355: #---- Called from the listStudents routine
1.249     albertel 1356: 
                   1357: sub check_script {
1.596.2.12.2.  1(raebur 1358:0):     my ($form,$type) = @_;
                   1359:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1360:     function checkall() {
                   1361:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1362:             ele = document.forms.'.$form.'.elements[i];
                   1363:             if (ele.name == "'.$type.'") {
                   1364:             document.forms.'.$form.'.elements[i].checked=true;
                   1365:                                        }
                   1366:         }
                   1367:     }
                   1368: 
                   1369:     function checksec() {
                   1370:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1371:             ele = document.forms.'.$form.'.elements[i];
                   1372:            string = document.forms.'.$form.'.chksec.value;
                   1373:            if
                   1374:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1375:               document.forms.'.$form.'.elements[i].checked=true;
                   1376:             }
                   1377:         }
                   1378:     }
                   1379: 
                   1380: 
                   1381:     function uncheckall() {
                   1382:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1383:             ele = document.forms.'.$form.'.elements[i];
                   1384:             if (ele.name == "'.$type.'") {
                   1385:             document.forms.'.$form.'.elements[i].checked=false;
                   1386:                                        }
                   1387:         }
                   1388:     }
                   1389: 
1.596.2.12.2.  1(raebur 1390:0): '."\n");
1.249     albertel 1391:     return $chkallscript;
                   1392: }
                   1393: 
                   1394: sub check_buttons {
1.485     albertel 1395:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1396:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1397:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1398:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1399:     return $buttons;
                   1400: }
                   1401: 
1.44      ng       1402: #     Displays the submissions for one student or a group of students
1.34      ng       1403: sub processGroup {
1.596.2.12.2.  1(raebur 1404:0):     my ($request,$symb) = @_;
1.41      ng       1405:     my $ctr        = 0;
1.155     albertel 1406:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1407:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1408: 
1.396     banghart 1409:     foreach my $student (@stuchecked) {
                   1410: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1411: 	$env{'form.student'}        = $uname;
                   1412: 	$env{'form.userdom'}        = $udom;
                   1413: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1414:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1415: 	$ctr++;
                   1416:     }
                   1417:     return '';
1.35      ng       1418: }
1.34      ng       1419: 
1.44      ng       1420: #------------------------------------------------------------------------------------
                   1421: #
                   1422: #-------------------------- Next few routines handles grading by student, essentially
                   1423: #                           handles essay response type problem/part
                   1424: #
                   1425: #--- Javascript to handle the submission page functionality ---
                   1426: sub sub_page_js {
                   1427:     my $request = shift;
1.596.2.12.2.  6(raebur 1428:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1429:6):     &js_escape(\$alertmsg);
          1(raebur 1430:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1431:     function updateRadio(formname,id,weight) {
1.125     ng       1432: 	var gradeBox = formname["GD_BOX"+id];
                   1433: 	var radioButton = formname["RADVAL"+id];
                   1434: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1435: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1436: 	gradeBox.value = pts;
                   1437: 	var resetbox = false;
                   1438: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1439: 	    alert("$alertmsg"+pts);
1.71      ng       1440: 	    for (var i=0; i<radioButton.length; i++) {
                   1441: 		if (radioButton[i].checked) {
                   1442: 		    gradeBox.value = i;
                   1443: 		    resetbox = true;
                   1444: 		}
                   1445: 	    }
                   1446: 	    if (!resetbox) {
                   1447: 		formtextbox.value = "";
                   1448: 	    }
                   1449: 	    return;
1.44      ng       1450: 	}
1.71      ng       1451: 
                   1452: 	if (pts > weight) {
                   1453: 	    var resp = confirm("You entered a value ("+pts+
                   1454: 			       ") greater than the weight for the part. Accept?");
                   1455: 	    if (resp == false) {
1.125     ng       1456: 		gradeBox.value = oldpts;
1.71      ng       1457: 		return;
                   1458: 	    }
1.44      ng       1459: 	}
1.13      albertel 1460: 
1.71      ng       1461: 	for (var i=0; i<radioButton.length; i++) {
                   1462: 	    radioButton[i].checked=false;
                   1463: 	    if (pts == i && pts != "") {
                   1464: 		radioButton[i].checked=true;
                   1465: 	    }
                   1466: 	}
                   1467: 	updateSelect(formname,id);
1.125     ng       1468: 	formname["stores"+id].value = "0";
1.41      ng       1469:     }
1.5       albertel 1470: 
1.72      ng       1471:     function writeBox(formname,id,pts) {
1.125     ng       1472: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1473: 	if (checkSolved(formname,id) == 'update') {
                   1474: 	    gradeBox.value = pts;
                   1475: 	} else {
1.125     ng       1476: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1477: 	    gradeBox.value = oldpts;
1.125     ng       1478: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1479: 	    for (var i=0; i<radioButton.length; i++) {
                   1480: 		radioButton[i].checked=false;
1.72      ng       1481: 		if (i == oldpts) {
1.71      ng       1482: 		    radioButton[i].checked=true;
                   1483: 		}
                   1484: 	    }
1.41      ng       1485: 	}
1.125     ng       1486: 	formname["stores"+id].value = "0";
1.71      ng       1487: 	updateSelect(formname,id);
                   1488: 	return;
1.41      ng       1489:     }
1.44      ng       1490: 
1.71      ng       1491:     function clearRadBox(formname,id) {
                   1492: 	if (checkSolved(formname,id) == 'noupdate') {
                   1493: 	    updateSelect(formname,id);
                   1494: 	    return;
                   1495: 	}
1.125     ng       1496: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1497: 	for (var i=0; i<gradeSelect.length; i++) {
                   1498: 	    if (gradeSelect[i].selected) {
                   1499: 		var selectx=i;
                   1500: 	    }
                   1501: 	}
1.125     ng       1502: 	var stores = formname["stores"+id];
1.71      ng       1503: 	if (selectx == stores.value) { return };
1.125     ng       1504: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1505: 	gradeBox.value = "";
1.125     ng       1506: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1507: 	for (var i=0; i<radioButton.length; i++) {
                   1508: 	    radioButton[i].checked=false;
                   1509: 	}
                   1510: 	stores.value = selectx;
                   1511:     }
1.5       albertel 1512: 
1.71      ng       1513:     function checkSolved(formname,id) {
1.125     ng       1514: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1515: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1516: 	    if (!reply) {return "noupdate";}
1.120     ng       1517: 	    formname.overRideScore.value = 'yes';
1.41      ng       1518: 	}
1.71      ng       1519: 	return "update";
1.13      albertel 1520:     }
1.71      ng       1521: 
                   1522:     function updateSelect(formname,id) {
1.125     ng       1523: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1524: 	return;
1.41      ng       1525:     }
1.33      ng       1526: 
1.121     ng       1527: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1528:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1529: 	formname.gradeOpt.value = val;
1.71      ng       1530: 	if (val == "Save & Next") {
                   1531: 	    for (i=0;i<=total;i++) {
                   1532: 		for (j=0;j<parttot;j++) {
1.125     ng       1533: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1534: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1535: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1536: 			if (points == "") {
1.125     ng       1537: 			    var name = formname["name"+i].value;
1.129     ng       1538: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1539: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1540: 					       ", part "+partid+". Continue?");
1.71      ng       1541: 			    if (resp == false) {
1.125     ng       1542: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1543: 				return false;
                   1544: 			    }
                   1545: 			}
                   1546: 		    }
                   1547: 		}
                   1548: 	    }
                   1549: 	}
1.120     ng       1550: 	formname.submit();
                   1551:     }
                   1552: 
1.71      ng       1553: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1554:     function checkSubmitPage(formname,total) {
                   1555: 	noscore = new Array(100);
                   1556: 	var ptr = 0;
                   1557: 	for (i=1;i<total;i++) {
1.125     ng       1558: 	    var partid = formname["q_"+i].value;
1.127     ng       1559: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1560: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1561: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1562: 		if (points == "" && status != "correct_by_student") {
                   1563: 		    noscore[ptr] = i;
                   1564: 		    ptr++;
                   1565: 		}
                   1566: 	    }
                   1567: 	}
                   1568: 	if (ptr != 0) {
                   1569: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1570: 	    var prolist = "";
                   1571: 	    if (ptr == 1) {
                   1572: 		prolist = noscore[0];
                   1573: 	    } else {
                   1574: 		var i = 0;
                   1575: 		while (i < ptr-1) {
                   1576: 		    prolist += noscore[i]+", ";
                   1577: 		    i++;
                   1578: 		}
                   1579: 		prolist += "and "+noscore[i];
                   1580: 	    }
                   1581: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1582: 	    if (resp == false) {
                   1583: 		return false;
                   1584: 	    }
                   1585: 	}
1.45      ng       1586: 
1.71      ng       1587: 	formname.submit();
                   1588:     }
                   1589: SUBJAVASCRIPT
                   1590: }
1.45      ng       1591: 
1.596.2.12.2.  1(raebur 1592:0): #--- javascript for grading message center
                   1593:0): sub sub_grademessage_js {
1.71      ng       1594:     my $request = shift;
1.80      ng       1595:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1596:     &commonJSfunctions($request);
1.350     albertel 1597: 
1.596.2.12.2.  1(raebur 1598:0):     my $inner_js_msg_central= (<<INNERJS);
                   1599:0): <script type="text/javascript">
1.350     albertel 1600:     function checkInput() {
                   1601:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1602:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1603:       var usrctr = document.msgcenter.usrctr.value;
                   1604:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1605:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1606: 
                   1607:       var msgchk = "";
                   1608:       if (document.msgcenter.subchk.checked) {
                   1609:          msgchk = "msgsub,";
                   1610:       }
                   1611:       var includemsg = 0;
                   1612:       for (var i=1; i<=nmsg; i++) {
                   1613:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1614:           var frmmsg = document.msgcenter["msg"+i];
                   1615:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1616:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1617:           showflg.value = "1";
                   1618:           var chkbox = document.msgcenter["msgn"+i];
                   1619:           if (chkbox.checked) {
                   1620:              msgchk += "savemsg"+i+",";
                   1621:              includemsg = 1;
                   1622:           }
                   1623:       }
                   1624:       if (document.msgcenter.newmsgchk.checked) {
                   1625:          msgchk += "newmsg"+usrctr;
                   1626:          includemsg = 1;
                   1627:       }
                   1628:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1629:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1630:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1631:       includemsg.value = msgchk;
                   1632: 
                   1633:       self.close()
                   1634: 
                   1635:     }
1.351     albertel 1636: </script>
                   1637: INNERJS
                   1638: 
1.596.2.12.2.  1(raebur 1639:0):     my $start_page_msg_central =
1.351     albertel 1640:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1641: 				       {'js_ready'  => 1,
                   1642: 					'only_body' => 1,
                   1643: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1644:0):     my $end_page_msg_central =
1.351     albertel 1645: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1646: 
                   1647: 
1.219     www      1648:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1649:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1650:0): 
          6(raebur 1651:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1652:                 comp => 'Compose Message for: ',
                   1653:                 incl => 'Include',
                   1654:                 type => 'Type',
                   1655:                 subj => 'Subject',
                   1656:                 mesa => 'Message',
                   1657:                 new  => 'New',
                   1658:                 save => 'Save',
                   1659:                 canc => 'Cancel',
                   1660:              );
1.596.2.12.2.  6(raebur 1661:6):     &html_escape(\%html_js_lt);
                   1662:6):     &js_escape(\%html_js_lt);
          1(raebur 1663:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1664: 
                   1665: //===================== Script to view submitted by ==================
                   1666:   function viewSubmitter(submitter) {
                   1667:     document.SCORE.refresh.value = "on";
                   1668:     document.SCORE.NCT.value = "1";
                   1669:     document.SCORE.unamedom0.value = submitter;
                   1670:     document.SCORE.submit();
                   1671:     return;
                   1672:   }
                   1673: 
                   1674: //====================== Script for composing message ==============
1.80      ng       1675:    // preload images
                   1676:    img1 = new Image();
                   1677:    img1.src = "$iconpath/mailbkgrd.gif";
                   1678:    img2 = new Image();
                   1679:    img2.src = "$iconpath/mailto.gif";
                   1680: 
1.44      ng       1681:   function msgCenter(msgform,usrctr,fullname) {
                   1682:     var Nmsg  = msgform.savemsgN.value;
                   1683:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1684:     var subject = msgform.msgsub.value;
1.127     ng       1685:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1686:     re = /msgsub/;
                   1687:     var shwsel = "";
                   1688:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1689:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1690:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1691:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1692: 	var testmsg = "savemsg"+i+",";
                   1693: 	re = new RegExp(testmsg,"g");
1.44      ng       1694: 	shwsel = "";
                   1695: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1696: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1697: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1698: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1699: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1700:     }
1.125     ng       1701:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1702:     shwsel = "";
                   1703:     re = /newmsg/;
                   1704:     if (re.test(msgchk)) { shwsel = "checked" }
                   1705:     newMsg(newmsg,shwsel);
                   1706:     msgTail(); 
                   1707:     return;
                   1708:   }
                   1709: 
1.123     ng       1710:   function checkEntities(strx) {
                   1711:     if (strx.length == 0) return strx;
                   1712:     var orgStr = ["&", "<", ">", '"']; 
                   1713:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1714:     var counter = 0;
                   1715:     while (counter < 4) {
                   1716: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1717: 	counter++;
                   1718:     }
                   1719:     return strx;
                   1720:   }
                   1721: 
                   1722:   function strReplace(strx, orgStr, newStr) {
                   1723:     return strx.split(orgStr).join(newStr);
                   1724:   }
                   1725: 
1.44      ng       1726:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1727:     var height = 70*Nmsg+250;
1.44      ng       1728:     if (height > 600) {
                   1729: 	height = 600;
                   1730:     }
1.118     ng       1731:     var xpos = (screen.width-600)/2;
                   1732:     xpos = (xpos < 0) ? '0' : xpos;
                   1733:     var ypos = (screen.height-height)/2-30;
                   1734:     ypos = (ypos < 0) ? '0' : ypos;
                   1735: 
1.596.2.12.2.  (raeburn 1736:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1737:     pWin.focus();
                   1738:     pDoc = pWin.document;
1.219     www      1739:     pDoc.$docopen;
1.351     albertel 1740:     pDoc.write('$start_page_msg_central');
1.76      ng       1741: 
                   1742:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1743:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1744:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1745: 
1.596.2.12.2.  1(raebur 1746:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1747:0):     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1748: }
                   1749:     function displaySubject(msg,shwsel) {
1.76      ng       1750:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1751:0):     pDoc.write("<tr>");
1.465     albertel 1752:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1753:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1754:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1755: }
                   1756: 
1.72      ng       1757:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1758:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1759:0):     pDoc.write("<tr>");
1.465     albertel 1760:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1761:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1762:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1763: }
                   1764: 
                   1765:   function newMsg(newmsg,shwsel) {
1.76      ng       1766:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1767:0):     pDoc.write("<tr>");
1.465     albertel 1768:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1769:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1770:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1771: }
                   1772: 
                   1773:   function msgTail() {
1.76      ng       1774:     pDoc = pWin.document;
1.465     albertel 1775:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1776:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1777:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1778:     pDoc.write("<\\/form>");
1.351     albertel 1779:     pDoc.write('$end_page_msg_central');
1.128     ng       1780:     pDoc.close();
1.44      ng       1781: }
                   1782: 
1.596.2.12.2.  1(raebur 1783:0): SUBJAVASCRIPT
                   1784:0): }
                   1785:0): 
                   1786:0): #--- javascript for essay type problem --
                   1787:0): sub sub_page_kw_js {
                   1788:0):     my $request = shift;
                   1789:0): 
                   1790:0):     unless ($env{'form.compmsg'}) {
                   1791:0):         &commonJSfunctions($request);
                   1792:0):     }
                   1793:0): 
                   1794:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1795:0): <script type="text/javascript">
                   1796:0):     function updateChoice(flag) {
                   1797:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1798:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1799:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1800:0):       opener.document.SCORE.refresh.value = "on";
                   1801:0):       if (opener.document.SCORE.keywords.value!=""){
                   1802:0):          opener.document.SCORE.submit();
                   1803:0):       }
                   1804:0):       self.close()
                   1805:0):     }
                   1806:0): </script>
                   1807:0): INNERJS
                   1808:0): 
                   1809:0):     my $start_page_highlight_central =
                   1810:0):         &Apache::loncommon::start_page('Highlight Central',
                   1811:0):                                        $inner_js_highlight_central,
                   1812:0):                                        {'js_ready'  => 1,
                   1813:0):                                         'only_body' => 1,
                   1814:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1815:0):     my $end_page_highlight_central =
                   1816:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1817:0): 
                   1818:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1819:0):     $docopen=~s/^document\.//;
                   1820:0): 
                   1821:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1822:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1823:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1824:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1825:0):                 col1 => 'red',
                   1826:0):                 col2 => 'green',
                   1827:0):                 col3 => 'blue',
                   1828:0):                 siz1 => 'normal',
                   1829:0):                 siz2 => '+1',
                   1830:0):                 siz3 => '+2',
                   1831:0):                 sty1 => 'normal',
                   1832:0):                 sty2 => 'italic',
                   1833:0):                 sty3 => 'bold',
                   1834:0):              );
                   1835:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1836:0):                 save => 'Save',
                   1837:0):                 canc => 'Cancel',
                   1838:0):                 kehi => 'Keyword Highlight Options',
                   1839:0):                 txtc => 'Text Color',
                   1840:0):                 font => 'Font Size',
                   1841:0):                 fnst => 'Font Style',
                   1842:0):              );
                   1843:0):     &js_escape(\%js_lt);
                   1844:0):     &html_escape(\%html_js_lt);
                   1845:0):     &js_escape(\%html_js_lt);
                   1846:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1847:0): 
                   1848:0): //===================== Show list of keywords ====================
                   1849:0):   function keywords(formname) {
                   1850:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1851:0):     if (nret==null) return;
                   1852:0):     formname.keywords.value = nret;
                   1853:0): 
                   1854:0):     if (formname.keywords.value != "") {
                   1855:0):         formname.refresh.value = "on";
                   1856:0):         formname.submit();
                   1857:0):     }
                   1858:0):     return;
                   1859:0):   }
                   1860:0): 
                   1861:0): //===================== Script to add keyword(s) ==================
                   1862:0):   function getSel() {
                   1863:0):     if (document.getSelection) txt = document.getSelection();
                   1864:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1865:0):     else return;
                   1866:0):     if (typeof(txt) != 'string') {
                   1867:0):         txt = String(txt);
                   1868:0):     }
                   1869:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1870:0):     if (cleantxt=="") {
                   1871:0):         alert("$js_lt{'plse'}");
                   1872:0):         return;
                   1873:0):     }
                   1874:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1875:0):     if (nret==null) return;
                   1876:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1877:0):     if (document.SCORE.keywords.value != "") {
                   1878:0):         document.SCORE.refresh.value = "on";
                   1879:0):         document.SCORE.submit();
                   1880:0):     }
                   1881:0):     return;
                   1882:0):   }
                   1883:0): 
1.44      ng       1884: //====================== Script for keyword highlight options ==============
                   1885:   function kwhighlight() {
                   1886:     var kwclr    = document.SCORE.kwclr.value;
                   1887:     var kwsize   = document.SCORE.kwsize.value;
                   1888:     var kwstyle  = document.SCORE.kwstyle.value;
                   1889:     var redsel = "";
                   1890:     var grnsel = "";
                   1891:     var blusel = "";
1.596.2.12.2.  6(raebur 1892:6):     var txtcol1 = "$js_lt{'col1'}";
                   1893:6):     var txtcol2 = "$js_lt{'col2'}";
                   1894:6):     var txtcol3 = "$js_lt{'col3'}";
                   1895:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1896:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1897:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1898:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1899:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1900:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1901:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1902:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1903:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1904:     var sznsel = "";
                   1905:     var sz1sel = "";
                   1906:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1907:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1908:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1909:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1910:     var synsel = "";
                   1911:     var syisel = "";
                   1912:     var sybsel = "";
1.596.2.12.2.  8(raebur 1913:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1914:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1915:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1916:     highlightCentral();
1.596.2.12.2.  8(raebur 1917:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1918:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1919:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1920:     highlightend();
                   1921:     return;
                   1922:   }
                   1923: 
                   1924:   function highlightCentral() {
1.76      ng       1925: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1926:     var xpos = (screen.width-400)/2;
                   1927:     xpos = (xpos < 0) ? '0' : xpos;
                   1928:     var ypos = (screen.height-330)/2-30;
                   1929:     ypos = (ypos < 0) ? '0' : ypos;
                   1930: 
1.206     albertel 1931:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1932:     hwdWin.focus();
                   1933:     var hDoc = hwdWin.document;
1.219     www      1934:     hDoc.$docopen;
1.351     albertel 1935:     hDoc.write('$start_page_highlight_central');
1.76      ng       1936:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1937:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1938: 
1.596.2.12.2.  8(raebur 1939:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1940:6):     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1941:   }
                   1942: 
                   1943:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1944:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1945:4):     hDoc.write("<tr>");
1.76      ng       1946:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1947:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1948:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1949:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1950:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1951:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1952:     hDoc.write("<\\/tr>");
1.44      ng       1953:   }
                   1954: 
                   1955:   function highlightend() { 
1.76      ng       1956:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1957:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1958:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1959:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1960:     hDoc.write("<\\/form>");
1.351     albertel 1961:     hDoc.write('$end_page_highlight_central');
1.128     ng       1962:     hDoc.close();
1.44      ng       1963:   }
                   1964: 
                   1965: SUBJAVASCRIPT
                   1966: }
                   1967: 
1.349     albertel 1968: sub get_increment {
1.348     bowersj2 1969:     my $increment = $env{'form.increment'};
                   1970:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1971:         $increment != .1) {
                   1972:         $increment = 1;
                   1973:     }
                   1974:     return $increment;
                   1975: }
                   1976: 
1.585     bisitz   1977: sub gradeBox_start {
                   1978:     return (
                   1979:         &Apache::loncommon::start_data_table()
                   1980:        .&Apache::loncommon::start_data_table_header_row()
                   1981:        .'<th>'.&mt('Part').'</th>'
                   1982:        .'<th>'.&mt('Points').'</th>'
                   1983:        .'<th>&nbsp;</th>'
                   1984:        .'<th>'.&mt('Assign Grade').'</th>'
                   1985:        .'<th>'.&mt('Weight').'</th>'
                   1986:        .'<th>'.&mt('Grade Status').'</th>'
                   1987:        .&Apache::loncommon::end_data_table_header_row()
                   1988:     );
                   1989: }
                   1990: 
                   1991: sub gradeBox_end {
                   1992:     return (
                   1993:         &Apache::loncommon::end_data_table()
                   1994:     );
                   1995: }
1.71      ng       1996: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1997: sub gradeBox {
1.322     albertel 1998:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1999:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 2000: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       2001:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 2002:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   2003:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       2004:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   2005:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 2006: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 2007:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 2008:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 2009:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2010: 				       [$partid]);
                   2011:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2012:     if ($last_resets{$partid}) {
                   2013:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2014:     }
1.596.2.12.2.  8(raebur 2015:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2016:     my $ctr = 0;
1.348     bowersj2 2017:     my $thisweight = 0;
1.349     albertel 2018:     my $increment = &get_increment();
1.485     albertel 2019: 
                   2020:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2021:     while ($thisweight<=$wgt) {
1.532     bisitz   2022: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2023:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2024: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2025: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2026: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2027:         $thisweight += $increment;
1.71      ng       2028: 	$ctr++;
                   2029:     }
1.485     albertel 2030:     $radio.='</tr></table>';
                   2031: 
                   2032:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2033: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2034: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2035: 	$wgt.')" /></td>'."\n";
1.485     albertel 2036:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2037: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2038: 	' </td>'."\n";
                   2039:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2040: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2041:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2042: 	$line.='<option></option>'.
                   2043: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2044:     } else {
1.485     albertel 2045: 	$line.='<option selected="selected"></option>'.
                   2046: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2047:     }
1.485     albertel 2048:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2049: 
                   2050: 
                   2051:     $result .= 
1.596.2.12.2.  8(raebur 2052:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2053:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2054:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2055:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2056: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2057: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2058: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2059:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2060:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2061:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2062:         $aggtries.'" />'."\n";
1.582     raeburn  2063:     my $res_error;
                   2064:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2065:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2066:     if ($res_error) {
                   2067:         return &navmap_errormsg();
                   2068:     }
1.318     banghart 2069:     return $result;
                   2070: }
1.322     albertel 2071: 
                   2072: sub handback_box {
1.596.2.12.2.  1(raebur 2073:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2074:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2075:0):     return unless ($numessay);
1.323     banghart 2076:     my (@respids);
1.596.2.4  raeburn  2077:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2078:     foreach my $part_response_id (@part_response_id) {
                   2079:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2080:         if ($part eq $partid) {
1.375     albertel 2081:             push(@respids,$resp);
1.323     banghart 2082:         }
                   2083:     }
1.318     banghart 2084:     my $result;
1.323     banghart 2085:     foreach my $respid (@respids) {
1.322     albertel 2086: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2087: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2088: 	next if (!@$files);
1.596.2.4  raeburn  2089: 	my $file_counter = 0;
1.313     banghart 2090: 	foreach my $file (@$files) {
1.368     banghart 2091: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2092:                 $file_counter++;
1.368     banghart 2093:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2094:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2095:     	        $file_disp = "$name.$ext";
                   2096:     	        $file = $file_path.$file_disp;
                   2097:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2098:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2099:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2100:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2101: 	    }
1.322     albertel 2102: 	}
1.596.2.4  raeburn  2103:         if ($file_counter) {
                   2104:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2105:                        '<span class="LC_info">'.
                   2106:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2107:         }
1.313     banghart 2108:     }
1.318     banghart 2109:     return $result;    
1.71      ng       2110: }
1.44      ng       2111: 
1.58      albertel 2112: sub show_problem {
1.382     albertel 2113:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2114:     my $rendered;
1.382     albertel 2115:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2116:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2117:     if ($mode eq 'both' or $mode eq 'text') {
                   2118: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2119: 						       $env{'request.course.id'},
                   2120: 						       undef,\%form);
1.144     albertel 2121:     }
1.58      albertel 2122:     if ($removeform) {
                   2123: 	$rendered=~s|<form(.*?)>||g;
                   2124: 	$rendered=~s|</form>||g;
1.374     albertel 2125: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2126:     }
1.144     albertel 2127:     my $companswer;
                   2128:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2129: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2130: 	$companswer=
                   2131: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2132: 						    $env{'request.course.id'},
                   2133: 						    %form);
1.144     albertel 2134:     }
1.58      albertel 2135:     if ($removeform) {
                   2136: 	$companswer=~s|<form(.*?)>||g;
                   2137: 	$companswer=~s|</form>||g;
1.144     albertel 2138: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2139:     }
1.596.2.12.2.  (raeburn 2140:):     my $renderheading = &mt('View of the problem');
                   2141:):     my $answerheading = &mt('Correct answer');
                   2142:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2143:):         my $stu_fullname = $env{'form.fullname'};
                   2144:):         if ($stu_fullname eq '') {
                   2145:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2146:):         }
                   2147:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2148:):         if ($forwhom ne '') {
                   2149:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2150:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2151:):         }
                   2152:):     }
1.468     albertel 2153:     $rendered=
1.588     bisitz   2154:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2155:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2156:        .$rendered
                   2157:        .'</div>';
1.468     albertel 2158:     $companswer=
1.588     bisitz   2159:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2160:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2161:        .$companswer
                   2162:        .'</div>';
1.468     albertel 2163:     my $result;
1.144     albertel 2164:     if ($mode eq 'both') {
1.588     bisitz   2165:         $result=$rendered.$companswer;
1.144     albertel 2166:     } elsif ($mode eq 'text') {
1.588     bisitz   2167:         $result=$rendered;
1.144     albertel 2168:     } elsif ($mode eq 'answer') {
1.588     bisitz   2169:         $result=$companswer;
1.144     albertel 2170:     }
1.71      ng       2171:     return $result;
1.58      albertel 2172: }
1.397     albertel 2173: 
1.396     banghart 2174: sub files_exist {
                   2175:     my ($r, $symb) = @_;
                   2176:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2177:     foreach my $student (@students) {
                   2178:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2179:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2180: 					      $udom,$uname);
1.396     banghart 2181:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2182:         foreach my $submission (@$string) {
                   2183:             my ($partid,$respid) =
                   2184: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2185:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2186: 					   \%record);
                   2187:             return 1 if (@$files);
1.396     banghart 2188:         }
                   2189:     }
1.397     albertel 2190:     return 0;
1.396     banghart 2191: }
1.397     albertel 2192: 
1.394     banghart 2193: sub download_all_link {
                   2194:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2195:0):     unless (&files_exist($r, $symb)) {
                   2196:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2197:0):         return;
                   2198:0):     }
1.395     albertel 2199:     my $all_students = 
                   2200: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2201: 
                   2202:     my $parts =
                   2203: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2204: 
1.394     banghart 2205:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2206:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2207:                              'cgi.'.$identifier.'.symb' => $symb,
                   2208:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2209:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2210: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2211:0):     return;
                   2212:0): }
                   2213:0): 
                   2214:0): sub submit_download_link {
                   2215:0):     my ($request,$symb) = @_;
                   2216:0):     if (!$symb) { return ''; }
                   2217:0):     my $res_error;
                   2218:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2219:0):         &response_type($symb,\$res_error);
                   2220:0):     if ($res_error) {
                   2221:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2222:0):         return;
                   2223:0):     }
                   2224:0):     unless ($numessay) {
                   2225:0):         $request->print(&mt('No essayresponse items found'));
                   2226:0):         return;
                   2227:0):     }
                   2228:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2229:0):     if (@chosenparts) {
                   2230:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2231:0):                                           undef,undef,1));
                   2232:0):     }
                   2233:0):     if ($numessay) {
                   2234:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2235:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2236:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2237:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2238:0):         if (ref($fullname) eq 'HASH') {
                   2239:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2240:0):             if (@students) {
                   2241:0):                 @{$env{'form.stuinfo'}} = @students;
                   2242:0):                 if ($numdropbox) {
                   2243:0):                     &download_all_link($request,$symb);
                   2244:0):                 } else {
                   2245:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2246:0):                 }
                   2247:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2248:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2249:0):             } else {
                   2250:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2251:0):             }
                   2252:0):         } else {
                   2253:0):             $request->print(&mt('Could not retrieve student information'));
                   2254:0):         }
                   2255:0):     } else {
                   2256:0):         $request->print(&mt('No essayresponse items found'));
                   2257:0):     }
                   2258:0):     return;
1.394     banghart 2259: }
1.395     albertel 2260: 
1.432     banghart 2261: sub build_section_inputs {
                   2262:     my $section_inputs;
                   2263:     if ($env{'form.section'} eq '') {
                   2264:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2265:     } else {
                   2266:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2267:         foreach my $section (@sections) {
1.432     banghart 2268:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2269:         }
                   2270:     }
                   2271:     return $section_inputs;
                   2272: }
                   2273: 
1.44      ng       2274: # --------------------------- show submissions of a student, option to grade 
                   2275: sub submission {
1.596.2.12.2.  1(raebur 2276:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2277:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2278:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2279:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2280:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2281:0): 
1.324     albertel 2282:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2283:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          5(raebur 2284:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2285: 
                   2286:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2287:4):         $request->print(
                   2288:4):             '<span class="LC_warning">'.
                   2289:4):             &mt('Unable to view requested student.').
                   2290:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2291:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2292:4):             '</span>');
1.104     albertel 2293: 	return;
                   2294:     }
                   2295: 
1.596.2.12.2.  1(raebur 2296:0):     my $res_error;
                   2297:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2298:0):         &response_type($symb,\$res_error);
                   2299:0):     if ($res_error) {
                   2300:0):         $request->print(&navmap_errormsg());
                   2301:0):         return;
                   2302:0):     }
                   2303:0): 
1.257     albertel 2304:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2305:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2306:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1.596.2.12.2.  1(raebur 2307:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2308:0):         $env{'form.compmsg'} = 1;
                   2309:0):     }
1.257     albertel 2310:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2311:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2312: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2313: 	'/check.gif" height="16" border="0" />';
1.41      ng       2314: 
                   2315:     # header info
                   2316:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2317:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2318:0):         if (@chosenparts) {
                   2319:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2320:0):         } elsif ($divforres) {
                   2321:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2322:0):         } else {
                   2323:0):             $request->print('<br clear="all" />');
                   2324:0):         }
1.41      ng       2325: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2326:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2327:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2328: 
1.44      ng       2329: 	# option to display problem, only once else it cause problems 
                   2330:         # with the form later since the problem has a form.
1.257     albertel 2331: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2332: 	    my $mode;
1.257     albertel 2333: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2334: 		$mode='both';
1.257     albertel 2335: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2336: 		$mode='text';
1.257     albertel 2337: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2338: 		$mode='answer';
                   2339: 	    }
1.329     albertel 2340: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2341: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2342: 	}
1.441     www      2343: 
1.41      ng       2344: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2345:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2346: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2347: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2348: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2349:0): 	}
                   2350:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2351:0): 	# if this subroutine has been called once.
                   2352:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2353: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2354: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2355: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2356: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2357: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2358:0): 	}
                   2359:0): 	if ($env{'form.compmsg'}) {
                   2360:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2361:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2362: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2363: 	}
1.596.2.12.2.  1(raebur 2364:0): 
1.257     albertel 2365: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2366: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2367: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2368: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2369: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2370: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2371: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2372: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2373: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2374: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2375: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2376: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2377: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2378:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2379: 			&build_section_inputs().
1.326     albertel 2380: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2381: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2382: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2383:0): 	if ($env{'form.compmsg'}) {
                   2384:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2385:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2386:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2387:0): 	}
                   2388:0): 	if ($numessay) {
1.257     albertel 2389: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2390: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2391: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2392:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2393: 	}
1.596.2.12.2.  1(raebur 2394:0): 
1.41      ng       2395: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2396: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2397: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2398: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2399: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2400: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2401: 		'" />'."\n".
                   2402: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2403: 	    $cts++;
                   2404: 	}
                   2405: 	$request->print($prnmsg);
1.32      ng       2406: 
1.596.2.12.2.  1(raebur 2407:0): 	if ($numessay) {
1.596.2.4  raeburn  2408: 
                   2409:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2410:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2411:                           keyw => 'Keyword Options',
                   2412:                           list => 'List',
                   2413:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2414:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2415:                      );
1.88      www      2416: #
                   2417: # Print out the keyword options line
                   2418: #
1.596.2.12.2.  1(raebur 2419:0): 	    $request->print(
          8(raebur 2420:4):                 '<div class="LC_columnSection">'
                   2421:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2422:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2423:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2424:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2425:4):  class="page">'.$lt{'past'}.'</a>',
                   2426:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2427:4):                     {legend => $lt{'keyw'}})
                   2428:4):                .'</fieldset></div>'
                   2429:4):             );
                   2430:4): 
1.88      www      2431: #
                   2432: # Load the other essays for similarity check
                   2433: #
1.596.2.12.2.  5(raebur 2434:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2435:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2436:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2437:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2438:9):                 if ($cdom ne '' && $cnum ne '') {
                   2439:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2440:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2441:9):                         my $apath = $1.'_'.$id;
                   2442:9):                         $apath=~s/\W/\_/gs;
                   2443:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2444:9):                     }
                   2445:9):                 }
                   2446:9):             } else {
                   2447:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2448:9): 	        $apath=&escape($apath);
                   2449:9): 	        $apath=~s/\W/\_/gs;
                   2450:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2451:9):             }
1.41      ng       2452:         }
                   2453:     }
1.44      ng       2454: 
1.441     www      2455: # This is where output for one specific student would start
1.592     bisitz   2456:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2457:     $request->print(
                   2458:         "\n\n"
                   2459:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2460:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2461:        ."\n"
                   2462:     );
1.441     www      2463: 
1.592     bisitz   2464:     # Show additional functions if allowed
                   2465:     if ($perm{'vgr'}) {
                   2466:         $request->print(
                   2467:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2468:3):                 'View recent activity',
1.592     bisitz   2469:                 $uname,$udom,'check')
                   2470:            .' '
                   2471:         );
                   2472:     }
                   2473:     if ($perm{'opa'}) {
                   2474:         $request->print(
                   2475:             &Apache::loncommon::pprmlink(
                   2476:                 &mt('Set/Change parameters'),
                   2477:                 $uname,$udom,$symb,'check'));
                   2478:     }
                   2479: 
                   2480:     # Show Problem
1.257     albertel 2481:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2482: 	my $mode;
1.257     albertel 2483: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2484: 	    $mode='both';
1.257     albertel 2485: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2486: 	    $mode='text';
1.257     albertel 2487: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2488: 	    $mode='answer';
                   2489: 	}
1.329     albertel 2490: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2491: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2492:     }
1.144     albertel 2493: 
1.257     albertel 2494:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2495: 
1.44      ng       2496:     # Display student info
1.41      ng       2497:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2498: 
                   2499:     my $result='<div class="LC_Box">'
                   2500:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2501:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2502:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  1(raebur 2503:0):     if ($numresp > $numessay) {
1.588     bisitz   2504:         $result.='<p class="LC_info">'
                   2505:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2506:                 ."</p>\n";
1.469     albertel 2507:     }
                   2508: 
1.596.2.12.2.  1(raebur 2509:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2510:     my $fullname;
                   2511:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2512:0):     if ($numessay) {
1.464     albertel 2513: 	(my $sub_result,$fullname,$col_fullnames)=
                   2514: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2515: 				 $counter);
                   2516: 	$result.=$sub_result;
1.41      ng       2517:     }
1.44      ng       2518:     $request->print($result."\n");
1.588     bisitz   2519: 
1.44      ng       2520:     # print student answer/submission
1.596.2.12.2.  1(raebur 2521:0):     # Options are (1) Last submission only
                   2522:0):     #             (2) Last submission (with detailed information for that submission)
                   2523:0):     #             (3) All transactions (by date)
                   2524:0):     #             (4) The whole record (with detailed information for all transactions)
                   2525:0): 
                   2526:0):     my ($string,$timestamp)= &get_last_submission(\%record);
                   2527:0): 
                   2528:0):     my $lastsubonly;
                   2529:0): 
                   2530:0):     if ($$timestamp eq '') {
                   2531:0):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2532:0):     } else {
                   2533:0):         $lastsubonly =
                   2534:0):             '<div class="LC_grade_submissions_body">'
                   2535:0):            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2536:0): 
                   2537:0): 	my %seenparts;
                   2538:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2539:0): 	foreach my $part (@part_response_id) {
                   2540:0): 	    my ($partid,$respid) = @{ $part };
                   2541:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2542:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2543:0): 		if (exists($seenparts{$partid})) { next; }
                   2544:0): 		$seenparts{$partid}=1;
                   2545:0):                 $request->print(
                   2546:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2547:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2548:0):                                '<a href="javascript:viewSubmitter(\''.
                   2549:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2550:0):                                '\');" target="_self">'.
                   2551:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2552:0):                     '<br />');
                   2553:0): 		next;
                   2554:0): 	    }
                   2555:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2556:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2557:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2558:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2559:0):                     ' <span class="LC_internal_info">'.
                   2560:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2561:0):                     '</span>&nbsp; &nbsp;'.
                   2562:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2563:0): 		next;
                   2564:0): 	    }
                   2565:0): 	    foreach my $submission (@$string) {
                   2566:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2567:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2568:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2569:0): 		# Similarity check
                   2570:0):                 my $similar='';
                   2571:0):                 my ($type,$trial,$rndseed);
                   2572:0):                 if ($hide eq 'rand') {
                   2573:0):                     $type = 'randomizetry';
                   2574:0):                     $trial = $record{"resource.$partid.tries"};
                   2575:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2576:0):                 }
                   2577:0): 		if ($env{'form.checkPlag'}) {
                   2578:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2579:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2580:0): 		    if ($osim) {
                   2581:0): 		        $osim=int($osim*100.0);
                   2582:0):                         if ($hide eq 'anon') {
                   2583:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2584:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2585:0):                         } else {
                   2586:0): 			    $similar='<hr />';
                   2587:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2588:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2589:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2590:0):                                                 $osim,
                   2591:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2592:0):                                             '</span></h3>';
                   2593:0):                             } elsif ($ocrsid ne '') {
                   2594:0):                                 my %old_course_desc;
                   2595:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2596:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2597:9):                                 } else {
          1(raebur 2598:0):                                     my $args;
                   2599:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2600:0):                                         $args = {'one_time' => 1};
                   2601:0):                                     }
                   2602:0):                                     %old_course_desc =
                   2603:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2604:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2605:9):                                 }
          1(raebur 2606:0):                                 $similar .=
                   2607:0):                                     '<h3><span class="LC_warning">'.
                   2608:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2609:0): 				        $osim,
                   2610:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2611:0): 				        $old_course_desc{'description'},
                   2612:0): 				        $old_course_desc{'num'},
                   2613:0): 				        $old_course_desc{'domain'}).
                   2614:0): 				    '</span></h3>';
1.596     raeburn  2615:                             } else {
1.596.2.12.2.  1(raebur 2616:0):                                 $similar .=
                   2617:0):                                     '<h3><span class="LC_warning">'.
                   2618:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2619:0):                                         $osim,
                   2620:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2621:0):                                     '</span></h3>';
1.596     raeburn  2622:                             }
1.596.2.12.2.  1(raebur 2623:0):                             $similar .= '<blockquote><i>'.
                   2624:0):                                         &keywords_highlight($oessay).
                   2625:0):                                         '</i></blockquote><hr />';
                   2626:0): 		        }
                   2627:0):                     }
                   2628:0):                 }
                   2629:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2630:0):                                      undef,$type,$trial,$rndseed);
                   2631:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2632:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2633:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2634:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2635:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2636:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2637:0):                         ' <span class="LC_internal_info">'.
                   2638:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2639:0):                         '</span>&nbsp; &nbsp;';
                   2640:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2641:0): 		    if (@$files) {
1.596.2.2  raeburn  2642:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2643:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2644:                         } else {
1.596.2.12.2.  1(raebur 2645:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2646:0):                                          .'<br /><span class="LC_warning">';
                   2647:0):                             if(@$files == 1) {
                   2648:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2649:0):                             } else {
                   2650:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2651:4):                             }
          1(raebur 2652:0):                             $lastsubonly .= '</span>';
                   2653:0):                             foreach my $file (@$files) {
                   2654:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2655:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2656:4):                             }
1.596     raeburn  2657:                         }
1.596.2.12.2.  1(raebur 2658:0): 			$lastsubonly.='<br />';
1.41      ng       2659: 		    }
1.596.2.12.2.  1(raebur 2660:0):                     if ($hide eq 'anon') {
                   2661:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2662:0):                     } else {
                   2663:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2664:0):                         if ($draft) {
                   2665:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2666:0):                         }
                   2667:0):                         $subval =
                   2668:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2669:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2670:0):                         if ($responsetype eq 'essay') {
                   2671:0):                             $subval =~ s{\n}{<br />}g;
                   2672:0):                         }
                   2673:0):                         $lastsubonly.=$subval."\n";
                   2674:0):                     }
                   2675:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2676:0): 		    $lastsubonly.='</div>';
1.41      ng       2677: 		}
                   2678: 	    }
1.151     albertel 2679: 	}
1.596.2.12.2.  1(raebur 2680:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2681:0):     }
                   2682:0):     $request->print($lastsubonly);
                   2683:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2684:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2685: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2686:3):     }
                   2687:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2688:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2689: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2690: 								 $env{'request.course.id'},
1.44      ng       2691: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2692:5): 								 'Apache::grades::keywords_highlight',
                   2693:5):                                                                  $usec,$identifier));
1.41      ng       2694:     }
1.121     ng       2695:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2696: 	.$udom.'" />'."\n");
1.44      ng       2697:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2698:0):     if (!&canmodify($usec)) {
                   2699:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2700:0):         return;
1.180     albertel 2701:     } else {
1.468     albertel 2702: 	$request->print('</div>'."\n");
1.41      ng       2703:     }
1.33      ng       2704: 
1.596.2.12.2.  1(raebur 2705:0):     # grading message center
                   2706:0): 
                   2707:0):     if ($env{'form.compmsg'}) {
                   2708:0):         my $result='<div class="LC_Box">'.
                   2709:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2710:0):                    '<div class="LC_grade_message_center_body">';
                   2711:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2712:0):         my $msgfor = $givenn.' '.$lastname;
                   2713:0):         if (scalar(@$col_fullnames) > 0) {
                   2714:0):             my $lastone = pop(@$col_fullnames);
                   2715:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2716:0):         }
                   2717:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2718:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2719:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2720:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2721:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2722:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2723:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2724:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2725:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2726:0):                  '<br />&nbsp;('.
                   2727:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2728:0): 	         '</div></div>';
                   2729:0):         $request->print($result);
1.118     ng       2730:     }
1.41      ng       2731: 
                   2732:     my %seen = ();
                   2733:     my @partlist;
1.129     ng       2734:     my @gradePartRespid;
1.375     albertel 2735:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2736:     $request->print(
1.588     bisitz   2737:         '<div class="LC_Box">'
                   2738:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2739:     );
1.592     bisitz   2740:     $request->print(&gradeBox_start());
1.375     albertel 2741:     foreach my $part_response_id (@part_response_id) {
                   2742:     	my ($partid,$respid) = @{ $part_response_id };
                   2743: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2744: 	next if ($seen{$partid} > 0);
1.41      ng       2745: 	$seen{$partid}++;
1.524     raeburn  2746: 	push(@partlist,$partid);
                   2747: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2748: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2749:     }
1.585     bisitz   2750:     $request->print(&gradeBox_end()); # </div>
                   2751:     $request->print('</div>');
1.468     albertel 2752: 
                   2753:     $request->print('<div class="LC_grade_info_links">');
                   2754:     $request->print('</div>');
                   2755: 
1.45      ng       2756:     $result='<input type="hidden" name="partlist'.$counter.
                   2757: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2758:     $result.='<input type="hidden" name="gradePartRespid'.
                   2759: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2760:     my $ctr = 0;
                   2761:     while ($ctr < scalar(@partlist)) {
                   2762: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2763: 	    $partlist[$ctr].'" />'."\n";
                   2764: 	$ctr++;
                   2765:     }
1.468     albertel 2766:     $request->print($result.''."\n");
1.41      ng       2767: 
1.441     www      2768: # Done with printing info for one student
                   2769: 
1.468     albertel 2770:     $request->print('</div>');#LC_grade_show_user
1.441     www      2771: 
                   2772: 
1.41      ng       2773:     # print end of form
                   2774:     if ($counter == $total) {
1.592     bisitz   2775:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2776: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2777: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2778: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2779: 	my $ntstu ='<select name="NTSTU">'.
                   2780: 	    '<option>1</option><option>2</option>'.
                   2781: 	    '<option>3</option><option>5</option>'.
                   2782: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2783: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2784: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2785:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2786: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2787: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2788: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2789: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2790:         $endform.='<span class="LC_warning">'.
                   2791:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2792:                   '</span>'."\n" ;
1.349     albertel 2793:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2794:             "' name='increment' />";
1.485     albertel 2795: 	$endform.='</td></tr></table></form>';
1.41      ng       2796: 	$request->print($endform);
                   2797:     }
                   2798:     return '';
1.38      ng       2799: }
                   2800: 
1.464     albertel 2801: sub check_collaborators {
                   2802:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2803:     my ($result,@col_fullnames);
                   2804:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2805:     foreach my $part (keys(%$handgrade)) {
                   2806: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2807: 					'.maxcollaborators',
                   2808: 					$symb,$udom,$uname);
                   2809: 	next if ($ncol <= 0);
                   2810: 	$part =~ s/\_/\./g;
                   2811: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2812: 	my (@good_collaborators, @bad_collaborators);
                   2813: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2814: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2815: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2816: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2817: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2818: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2819: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2820: 	    # Doing this grep allows 'fuzzy' specification
                   2821: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2822: 			       keys(%$classlist));
                   2823: 	    if (! scalar(@matches)) {
                   2824: 		push(@bad_collaborators, $possible_collaborator);
                   2825: 	    } else {
                   2826: 		push(@good_collaborators, @matches);
                   2827: 	    }
                   2828: 	}
                   2829: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2830: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2831: 	    foreach my $name (@good_collaborators) {
                   2832: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2833: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2834: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2835: 	    }
1.596.2.4  raeburn  2836: 	    $result.='</ol><br />'."\n";
1.466     albertel 2837: 	    my ($part)=split(/\./,$part);
1.464     albertel 2838: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2839: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2840: 		"\n";
                   2841: 	}
                   2842: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2843: 	    $result.='<div class="LC_warning">';
1.464     albertel 2844: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2845: 	    $result .= '</div>';
                   2846: 	}         
                   2847: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2848: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2849: 	    $result .= &mt('This student has submitted too many '.
                   2850: 		'collaborators.  Maximum is [_1].',$ncol);
                   2851: 	    $result .= '</div>';
                   2852: 	}
                   2853:     }
                   2854:     return ($result,$fullname,\@col_fullnames);
                   2855: }
                   2856: 
1.44      ng       2857: #--- Retrieve the last submission for all the parts
1.38      ng       2858: sub get_last_submission {
1.119     ng       2859:     my ($returnhash)=@_;
1.596     raeburn  2860:     my (@string,$timestamp,%lasthidden);
1.119     ng       2861:     if ($$returnhash{'version'}) {
1.46      ng       2862: 	my %lasthash=();
                   2863: 	my ($version);
1.119     ng       2864: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2865: 	    foreach my $key (sort(split(/\:/,
                   2866: 					$$returnhash{$version.':keys'}))) {
                   2867: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2868: 		$timestamp = 
1.545     raeburn  2869: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2870: 	    }
                   2871: 	}
1.596.2.2  raeburn  2872:         my (%typeparts,%randombytry);
1.596     raeburn  2873:         my $showsurv = 
                   2874:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2875:         foreach my $key (sort(keys(%lasthash))) {
                   2876:             if ($key =~ /\.type$/) {
                   2877:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2878:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2879:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2880:                     my ($ign,@parts) = split(/\./,$key);
                   2881:                     pop(@parts);
1.596.2.3  raeburn  2882:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2883:                     if ($lasthash{$key} eq 'randomizetry') {
                   2884:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2885:                     } else {
                   2886:                         unless ($showsurv) {
                   2887:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2888:                         }
1.596     raeburn  2889:                     }
                   2890:                     delete($lasthash{$key});
                   2891:                 }
                   2892:             }
                   2893:         }
                   2894:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2895:         my @randomize = keys(%randombytry);
1.397     albertel 2896: 	foreach my $key (keys(%lasthash)) {
                   2897: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2898:             my $hide;
                   2899:             if (@hidden) {
                   2900:                 foreach my $id (@hidden) {
                   2901:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2902:                         $hide = 'anon';
1.596     raeburn  2903:                         last;
                   2904:                     }
                   2905:                 }
                   2906:             }
1.596.2.2  raeburn  2907:             unless ($hide) {
                   2908:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2909:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2910:                         if ($key =~ /^\Q$id\E/) {
                   2911:                             $hide = 'rand';
                   2912:                             last;
                   2913:                         }
                   2914:                     }
                   2915:                 }
                   2916:             }
1.397     albertel 2917: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2918:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2919:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2920:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2921:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2922: 	}
                   2923:     }
1.397     albertel 2924:     if (!@string) {
                   2925: 	$string[0] =
1.539     riegler  2926: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2927:     }
                   2928:     return (\@string,\$timestamp);
1.38      ng       2929: }
1.35      ng       2930: 
1.44      ng       2931: #--- High light keywords, with style choosen by user.
1.38      ng       2932: sub keywords_highlight {
1.44      ng       2933:     my $string    = shift;
1.257     albertel 2934:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2935:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2936:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2937:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2938:     foreach my $keyword (@keylist) {
                   2939: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2940:     }
                   2941:     return $string;
1.38      ng       2942: }
1.36      ng       2943: 
1.596.2.12.2.  (raeburn 2944:): # For Tasks provide a mechanism to display previous version for one specific student
                   2945:): 
                   2946:): sub show_previous_task_version {
                   2947:):     my ($request,$symb) = @_;
                   2948:):     if ($symb eq '') {
          8(raebur 2949:4):         $request->print(
                   2950:4):             '<span class="LC_error">'.
                   2951:4):             &mt('Unable to handle ambiguous references.').
                   2952:4):             '</span>');
          (raeburn 2953:):         return '';
                   2954:):     }
                   2955:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2956:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2957:):     if (!&canview($usec)) {
          8(raebur 2958:4):         $request->print('<span class="LC_warning">'.
                   2959:4):                         &mt('Unable to view previous version for requested student.').
                   2960:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2961:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2962:4):                         '</span>');
          (raeburn 2963:):         return;
                   2964:):     }
                   2965:):     my $mode = 'both';
                   2966:):     my $isTask = ($symb =~/\.task$/);
                   2967:):     if ($isTask) {
                   2968:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2969:):             if ($env{'form.fullname'} eq '') {
                   2970:):                 $env{'form.fullname'} =
                   2971:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2972:):             }
                   2973:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2974:):             $request->print("\n\n".
                   2975:):                             '<div class="LC_grade_show_user">'.
                   2976:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2977:):                             '</h2>'."\n");
                   2978:):             &Apache::lonxml::clear_problem_counter();
                   2979:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2980:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2981:):             $request->print("\n</div>");
                   2982:):         }
                   2983:):     }
                   2984:):     return;
                   2985:): }
                   2986:): 
                   2987:): sub choose_task_version_form {
                   2988:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2989:):     my $isTask = ($symb =~/\.task$/);
                   2990:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2991:):     if ($isTask) {
                   2992:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2993:):                                               $udom,$uname);
                   2994:):         if (($record{'resource.0.version'} eq '') ||
                   2995:):             ($record{'resource.0.version'} < 2)) {
                   2996:):             return ($record{'resource.0.version'},
                   2997:):                     $record{'resource.0.version'},$result,$js);
                   2998:):         } else {
                   2999:):             $current = $record{'resource.0.version'};
                   3000:):         }
                   3001:):         if ($env{'form.previousversion'}) {
                   3002:):             $displayed = $env{'form.previousversion'};
                   3003:):             $rowtitle = &mt('Choose another version:')
                   3004:):         } else {
                   3005:):             $displayed = $current;
                   3006:):             $rowtitle = &mt('Show earlier version:');
                   3007:):         }
                   3008:):         $result = '<div class="LC_left_float">';
                   3009:):         my $list;
                   3010:):         my $numversions = 0;
                   3011:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3012:):             if ($i == $current) {
                   3013:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   3014:):                     next;
                   3015:):                 } else {
                   3016:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3017:):                     $numversions ++;
                   3018:):                 }
                   3019:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3020:):                 unless ($i == $env{'form.previousversion'}) {
                   3021:):                     $numversions ++;
                   3022:):                 }
                   3023:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3024:):             }
                   3025:):         }
                   3026:):         if ($numversions) {
                   3027:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3028:):             $result .=
                   3029:):                 '<form name="getprev" method="post" action=""'.
                   3030:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3031:):                 &Apache::loncommon::start_data_table().
                   3032:):                 &Apache::loncommon::start_data_table_row().
                   3033:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3034:):                 '<td><select name="version">'.
                   3035:):                 '<option>'.&mt('Select').'</option>'.
                   3036:):                 $list.
                   3037:):                 '</select></td>'.
                   3038:):                 &Apache::loncommon::end_data_table_row();
                   3039:):             unless ($nomenu) {
                   3040:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3041:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3042:):                 '<td><span class="LC_nobreak">'.
                   3043:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3044:):                 &mt('Yes').'</label>'.
                   3045:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3046:):                 '</span></td>'.
                   3047:):                 &Apache::loncommon::end_data_table_row();
                   3048:):             }
                   3049:):             $result .=
                   3050:):                 &Apache::loncommon::start_data_table_row().
                   3051:):                 '<th align="left">&nbsp;</th>'.
                   3052:):                 '<td>'.
                   3053:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3054:):                 '</td>'.
                   3055:):                 &Apache::loncommon::end_data_table_row().
                   3056:):                 &Apache::loncommon::end_data_table().
                   3057:):                 '</form>';
                   3058:):             $js = &previous_display_javascript($nomenu,$current);
                   3059:):         } elsif ($displayed && $nomenu) {
                   3060:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3061:):         } else {
                   3062:):             $result .= &mt('No previous versions to show for this student');
                   3063:):         }
                   3064:):         $result .= '</div>';
                   3065:):     }
                   3066:):     return ($current,$displayed,$result,$js);
                   3067:): }
                   3068:): 
                   3069:): sub previous_display_javascript {
                   3070:):     my ($nomenu,$current) = @_;
                   3071:):     my $js = <<"JSONE";
                   3072:): <script type="text/javascript">
                   3073:): // <![CDATA[
                   3074:): function previousVersion(uname,udom,symb) {
                   3075:):     var current = '$current';
                   3076:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3077:):     var prevstr = new RegExp("^\\\\d+\$");
                   3078:):     if (!prevstr.test(version)) {
                   3079:):         return false;
                   3080:):     }
                   3081:):     var url = '';
                   3082:):     if (version == current) {
                   3083:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3084:):     } else {
                   3085:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3086:):     }
                   3087:): JSONE
                   3088:):     if ($nomenu) {
                   3089:):         $js .= <<"JSTWO";
                   3090:):     document.location.href = url;
                   3091:): JSTWO
                   3092:):     } else {
                   3093:):         $js .= <<"JSTHREE";
                   3094:):     var newwin = 0;
                   3095:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3096:):         if (document.getprev.prevwin[i].checked == true) {
                   3097:):             newwin = document.getprev.prevwin[i].value;
                   3098:):         }
                   3099:):     }
                   3100:):     if (newwin == 1) {
                   3101:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3102:):         url = url+'&inhibitmenu=yes';
                   3103:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3104:):             previousWin = window.open(url,'',options,1);
                   3105:):         } else {
                   3106:):             previousWin.location.href = url;
                   3107:):         }
                   3108:):         previousWin.focus();
                   3109:):         return false;
                   3110:):     } else {
                   3111:):         document.location.href = url;
                   3112:):         return false;
                   3113:):     }
                   3114:): JSTHREE
                   3115:):     }
                   3116:):     $js .= <<"ENDJS";
                   3117:):     return false;
                   3118:): }
                   3119:): // ]]>
                   3120:): </script>
                   3121:): ENDJS
                   3122:): 
                   3123:): }
                   3124:): 
1.44      ng       3125: #--- Called from submission routine
1.38      ng       3126: sub processHandGrade {
1.596.2.12.2.  1(raebur 3127:0):     my ($request,$symb) = @_;
1.324     albertel 3128:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3129:     my $button = $env{'form.gradeOpt'};
                   3130:     my $ngrade = $env{'form.NCT'};
                   3131:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3132:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3133:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  8(raebur 3134:1):     my ($res_error,%queueable);
                   3135:1):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3136:1):     if ($res_error) {
                   3137:1):         $request->print(&navmap_errormsg());
                   3138:1):         return;
                   3139:1):     } else {
                   3140:1):         foreach my $part (@{$partlist}) {
                   3141:1):             if (ref($responseType->{$part}) eq 'HASH') {
                   3142:1):                 foreach my $id (keys(%{$responseType->{$part}})) {
                   3143:1):                     if (($responseType->{$part}->{$id} eq 'essay') ||
                   3144:1):                         (lc($handgrade->{$part.'_'.$id}) eq 'yes')) {
                   3145:1):                         $queueable{$part} = 1;
                   3146:1):                         last;
                   3147:1):                     }
                   3148:1):                 }
                   3149:1):             }
                   3150:1):         }
                   3151:1):     }
1.301     albertel 3152: 
1.44      ng       3153:     if ($button eq 'Save & Next') {
                   3154: 	my $ctr = 0;
                   3155: 	while ($ctr < $ngrade) {
1.257     albertel 3156: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3157:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
          8(raebur 3158:1):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr,undef,undef,\%queueable);
1.71      ng       3159: 	    if ($errorflag eq 'no_score') {
                   3160: 		$ctr++;
                   3161: 		next;
                   3162: 	    }
1.104     albertel 3163: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3164:4):                 $request->print(
                   3165:4):                     '<span class="LC_error">'
                   3166:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3167:4):                    .'</span>');
1.104     albertel 3168: 		$ctr++;
                   3169: 		next;
                   3170: 	    }
1.596.2.12.2.  1(raebur 3171:5):             if ($numhidden) {
                   3172:5):                 $request->print(
                   3173:5):                     '<span class="LC_info">'
                   3174:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3175:5):                    .'</span><br />');
                   3176:5):             }
1.257     albertel 3177: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3178: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3179: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3180:             my ($feedurl,$showsymb) =
                   3181: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3182: 	    my $messagetail;
1.62      albertel 3183: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3184: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3185: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3186: 		$subject.=' ['.$restitle.']';
1.44      ng       3187: 		my (@msgnum) = split(/,/,$includemsg);
                   3188: 		foreach (@msgnum) {
1.257     albertel 3189: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3190: 		}
1.80      ng       3191: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3192: 		if ($env{'form.withgrades'.$ctr}) {
                   3193: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3194: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3195:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3196: 		}
                   3197: 		$msgstatus = 
                   3198:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3199: 						     $message.$messagetail,
1.418     albertel 3200:                                                      undef,$feedurl,undef,
1.386     raeburn  3201:                                                      undef,undef,$showsymb,
                   3202:                                                      $restitle);
1.574     bisitz   3203: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3204: 				$msgstatus.'<br />');
1.44      ng       3205: 	    }
1.257     albertel 3206: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3207: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3208: 		foreach my $collabstr (@collabstrs) {
                   3209: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3210: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3211: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3212: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.596.2.12.2.  8(raebur 3213:1): 					   $env{'form.unamedom'.$ctr},$part,\%queueable);
1.150     albertel 3214: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3215: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3216: 			    next;
1.418     albertel 3217: 			} elsif ($message ne '') {
                   3218: 			    my ($baseurl,$showsymb) = 
                   3219: 				&get_feedurl_and_symb($symb,$collaborator,
                   3220: 						      $udom);
                   3221: 			    if ($env{'form.withgrades'.$ctr}) {
                   3222: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3223:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3224: 			    }
1.418     albertel 3225: 			    $msgstatus = 
                   3226: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3227: 			}
1.44      ng       3228: 		    }
                   3229: 		}
                   3230: 	    }
                   3231: 	    $ctr++;
                   3232: 	}
                   3233:     }
                   3234: 
1.596.2.12.2.  1(raebur 3235:0):     my %keyhash = ();
                   3236:0):     if ($numessay) {
1.119     ng       3237: 	# Keywords sorted in alphabatical order
1.257     albertel 3238: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3239: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3240:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3241: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3242: 	$env{'form.keywords'} = join(' ',@keywords);
                   3243: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3244: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3245: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3246: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3247: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3248:0):     }
1.119     ng       3249: 
1.596.2.12.2.  1(raebur 3250:0):     if ($env{'form.compmsg'}) {
1.119     ng       3251: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3252: 	# New messages are saved in env for the next student.
1.119     ng       3253: 	# All messages are saved in nohist_handgrade.db
                   3254: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3255: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3256: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3257: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3258: 		$idx++;
                   3259: 	    }
                   3260: 	    $ctr++;
1.41      ng       3261: 	}
1.119     ng       3262: 	$ctr = 0;
                   3263: 	while ($ctr < $ngrade) {
1.257     albertel 3264: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3265: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3266: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3267: 		$idx++;
                   3268: 	    }
                   3269: 	    $ctr++;
1.41      ng       3270: 	}
1.257     albertel 3271: 	$env{'form.savemsgN'} = --$idx;
                   3272: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3273:0):     }
                   3274:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3275: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3276: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3277:     }
1.596.2.12.2.  1(raebur 3278:0): 
1.44      ng       3279:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3280:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3281:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3282: 	my ($ctr,$total) = (0,0);
                   3283: 	while ($ctr < $ngrade) {
1.257     albertel 3284: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3285: 	    $ctr++;
                   3286: 	}
1.257     albertel 3287: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3288: 	$ctr = 0;
                   3289: 	while ($ctr < $total) {
1.257     albertel 3290: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3291: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3292: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3293:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3294: 	    $ctr++;
                   3295: 	}
                   3296: 	return '';
                   3297:     }
1.36      ng       3298: 
1.44      ng       3299:     # Get the next/previous one or group of students
1.257     albertel 3300:     my $firststu = $env{'form.unamedom0'};
                   3301:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3302:     my $ctr = 2;
1.41      ng       3303:     while ($laststu eq '') {
1.257     albertel 3304: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3305: 	$ctr++;
                   3306: 	$laststu = $firststu if ($ctr > $ngrade);
                   3307:     }
1.44      ng       3308: 
1.41      ng       3309:     my (@parsedlist,@nextlist);
                   3310:     my ($nextflg) = 0;
1.524     raeburn  3311:     foreach my $item (sort 
1.294     albertel 3312: 	     {
                   3313: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3314: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3315: 		 }
                   3316: 		 return $a cmp $b;
                   3317: 	     } (keys(%$fullname))) {
1.41      ng       3318: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3319: 	    push(@parsedlist,$item);
1.41      ng       3320: 	}
1.524     raeburn  3321: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3322: 	if ($button eq 'Previous') {
1.524     raeburn  3323: 	    last if ($item eq $firststu);
                   3324: 	    push(@parsedlist,$item);
1.41      ng       3325: 	}
                   3326:     }
                   3327:     $ctr = 0;
                   3328:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3329:     foreach my $student (@parsedlist) {
1.257     albertel 3330: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3331: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3332: 	
                   3333: 	if ($submitonly eq 'queued') {
                   3334: 	    my %queue_status = 
                   3335: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3336: 							$udom,$uname);
                   3337: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3338: 	}
                   3339: 
1.156     albertel 3340: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3341: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3342: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3343: 	    my $submitted = 0;
1.248     albertel 3344: 	    my $ungraded = 0;
                   3345: 	    my $incorrect = 0;
1.524     raeburn  3346: 	    foreach my $item (keys(%status)) {
                   3347: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3348: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3349: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3350: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3351: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3352: 		    $submitted = 0;
                   3353: 		}
1.41      ng       3354: 	    }
1.156     albertel 3355: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3356: 				     $submitonly eq 'incorrect' ||
                   3357: 				     $submitonly eq 'graded'));
1.248     albertel 3358: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3359: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3360: 	}
1.524     raeburn  3361: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3362: 	last if ($ctr == $ntstu);
1.41      ng       3363: 	$ctr++;
                   3364:     }
1.36      ng       3365: 
1.41      ng       3366:     $ctr = 0;
                   3367:     my $total = scalar(@nextlist)-1;
1.39      ng       3368: 
1.524     raeburn  3369:     foreach (sort(@nextlist)) {
1.41      ng       3370: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3371: 	$env{'form.student'}  = $uname;
                   3372: 	$env{'form.userdom'}  = $udom;
                   3373: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3374:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3375: 	$ctr++;
                   3376:     }
                   3377:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3378:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3379: 	$request->print($the_end);
                   3380:     }
                   3381:     return '';
1.38      ng       3382: }
1.36      ng       3383: 
1.44      ng       3384: #---- Save the score and award for each student, if changed
1.38      ng       3385: sub saveHandGrade {
1.596.2.12.2.  8(raebur 3386:1):     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part,$queueable) = @_;
1.342     banghart 3387:     my @version_parts;
1.104     albertel 3388:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3389: 					   $env{'request.course.id'});
1.104     albertel 3390:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3391:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3392:     my @parts_graded;
1.77      ng       3393:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3394:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3395:     my %aggregate = ();
                   3396:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3397:5):     if ($env{'form.HIDE'.$newflg}) {
                   3398:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3399:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3400:5):         $totchg += $numchgs;
                   3401:5):     }
1.301     albertel 3402:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3403:     foreach my $new_part (@parts) {
1.337     banghart 3404: 	#collaborator ($submi may vary for different parts
1.259     banghart 3405: 	if ($submitter && $new_part ne $part) { next; }
                   3406: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3407: 	if ($dropMenu eq 'excused') {
1.259     banghart 3408: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3409: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3410: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3411: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3412: 		}
1.364     banghart 3413: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3414: 	    }
1.125     ng       3415: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3416: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3417: 	    foreach my $key (keys(%record)) {
1.259     banghart 3418: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3419: 	    }
1.259     banghart 3420: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3421: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3422:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3423: 
                   3424:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3425: 					       [$new_part]);
                   3426:             my $aggtries =$totaltries;
1.269     raeburn  3427:             if ($last_resets{$new_part}) {
1.270     albertel 3428:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3429: 					   $new_part);
1.269     raeburn  3430:             }
1.270     albertel 3431: 
                   3432:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3433:             if ($aggtries > 0) {
1.327     albertel 3434:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3435:                 $aggregateflag = 1;
                   3436:             }
1.125     ng       3437: 	} elsif ($dropMenu eq '') {
1.259     banghart 3438: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3439: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3440: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3441: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3442: 		next;
                   3443: 	    }
1.259     banghart 3444: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3445: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3446: 	    my $partial= $pts/$wgt;
1.259     banghart 3447: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3448: 		#do not update score for part if not changed.
1.346     banghart 3449:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3450: 		next;
1.251     banghart 3451: 	    } else {
1.524     raeburn  3452: 	        push(@parts_graded,$new_part);
1.153     albertel 3453: 	    }
1.259     banghart 3454: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3455: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3456: 	    }
1.259     banghart 3457: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3458: 	    if ($partial == 0) {
1.153     albertel 3459: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3460: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3461: 		}
1.41      ng       3462: 	    } else {
1.153     albertel 3463: 		if ($record{$reckey} ne 'correct_by_override') {
                   3464: 		    $newrecord{$reckey} = 'correct_by_override';
                   3465: 		}
                   3466: 	    }	    
                   3467: 	    if ($submitter && 
1.259     banghart 3468: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3469: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3470: 	    }
1.259     banghart 3471: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3472: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3473: 	}
1.259     banghart 3474: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3475: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3476: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3477: 	        $dropMenu eq 'reset status')
                   3478: 	   {
1.524     raeburn  3479: 	    push(@version_parts,$new_part);
1.259     banghart 3480: 	}
1.41      ng       3481:     }
1.301     albertel 3482:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3483:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3484: 
1.344     albertel 3485:     if (%newrecord) {
                   3486:         if (@version_parts) {
1.364     banghart 3487:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3488:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3489: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3490: 	    foreach my $new_part (@version_parts) {
                   3491: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3492: 				$new_part,\%newrecord);
                   3493: 	    }
1.259     banghart 3494:         }
1.44      ng       3495: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3496: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3497: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
1.596.2.12.2.  8(raebur 3498:1): 				     $cdom,$cnum,$domain,$stuname,$queueable);
1.41      ng       3499:     }
1.269     raeburn  3500:     if ($aggregateflag) {
                   3501:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3502: 			      $cdom,$cnum);
1.269     raeburn  3503:     }
1.596.2.12.2.  1(raebur 3504:5):     return ('',$pts,$wgt,$totchg);
                   3505:5): }
                   3506:5): 
                   3507:5): sub makehidden {
                   3508:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3509:5):     return unless (ref($record) eq 'HASH');
                   3510:5):     my %modified;
                   3511:5):     my $numchanged = 0;
                   3512:5):     if (exists($record->{$version.':keys'})) {
                   3513:5):         my $partsregexp = $parts;
                   3514:5):         $partsregexp =~ s/,/|/g;
                   3515:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3516:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3517:5):                  my $item = $1;
                   3518:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3519:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3520:5):                  }
                   3521:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3522:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3523:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3524:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3525:5):             }
                   3526:5):         }
                   3527:5):         if (keys(%modified)) {
                   3528:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3529:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3530:5):                 $numchanged ++;
                   3531:5):             }
                   3532:5):         }
                   3533:5):     }
                   3534:5):     return $numchanged;
1.36      ng       3535: }
1.322     albertel 3536: 
1.380     albertel 3537: sub check_and_remove_from_queue {
1.596.2.12.2.  8(raebur 3538:1):     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname,$queueable) = @_;
1.380     albertel 3539:     my @ungraded_parts;
                   3540:     foreach my $part (@{$parts}) {
                   3541: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3542: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3543: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3544: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3545: 		) {
1.596.2.12.2.  8(raebur 3546:1):             if ($queueable->{$part}) {
                   3547:1): 	        push(@ungraded_parts, $part);
                   3548:1):             }
1.380     albertel 3549: 	}
                   3550:     }
                   3551:     if ( !@ungraded_parts ) {
                   3552: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3553: 					       $cnum,$domain,$stuname);
                   3554:     }
                   3555: }
                   3556: 
1.337     banghart 3557: sub handback_files {
                   3558:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3559:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3560:     my $res_error;
                   3561:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3562:     if ($res_error) {
                   3563:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3564:         return;
                   3565:     }
1.596.2.4  raeburn  3566:     my @handedback;
                   3567:     my $file_msg;
1.375     albertel 3568:     my @part_response_id = &flatten_responseType($responseType);
                   3569:     foreach my $part_response_id (@part_response_id) {
                   3570:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3571: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3572:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3573:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3574:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3575: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3576:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3577:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3578:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3579:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3580: 		        &file_name_version_ext($answer_file);
1.355     banghart 3581: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3582:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3583:):                     my ($dir_list,$listerror) =
                   3584:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3585:):                                                  $domain,$stuname,$getpropath);
                   3586:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3587:3):                     # fix filename
1.355     banghart 3588:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3589:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3590:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3591:             	                                $save_file_name);
1.337     banghart 3592:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3593:                         $request->print('<br /><span class="LC_error">'.
                   3594:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3595:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3596:                                         '</span>');
1.356     banghart 3597:                     } else {
1.360     banghart 3598:                         # mark the file as read only
1.596.2.4  raeburn  3599:                         push(@handedback,$save_file_name);
1.367     albertel 3600: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3601: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3602: 			}
                   3603:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3604: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3605: 
1.337     banghart 3606:                     }
1.596.2.12.2.  3(raebur 3607: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 3608:                 }
                   3609:             }
                   3610:         }
1.596.2.4  raeburn  3611:     }
                   3612:     if (@handedback > 0) {
                   3613:         $request->print('<br />');
                   3614:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3615:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3616:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3617:         my ($subject,$message);
                   3618:         if (scalar(@handedback) == 1) {
                   3619:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3620:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3621:         } else {
                   3622:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3623:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3624:         }
                   3625:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3626:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3627:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3628:         my ($feedurl,$showsymb) =
                   3629:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3630:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3631:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3632:         my $msgstatus =
                   3633:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3634:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3635:                  $restitle);
                   3636:         if ($msgstatus) {
                   3637:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3638:         }
                   3639:     }
1.338     banghart 3640:     return;
1.337     banghart 3641: }
                   3642: 
1.418     albertel 3643: sub get_feedurl_and_symb {
                   3644:     my ($symb,$uname,$udom) = @_;
                   3645:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3646:     $url = &Apache::lonnet::clutter($url);
                   3647:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3648: 					$symb,$udom,$uname);
                   3649:     if ($encrypturl =~ /^yes$/i) {
                   3650: 	&Apache::lonenc::encrypted(\$url,1);
                   3651: 	&Apache::lonenc::encrypted(\$symb,1);
                   3652:     }
                   3653:     return ($url,$symb);
                   3654: }
                   3655: 
1.313     banghart 3656: sub get_submitted_files {
                   3657:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3658:     my @files;
                   3659:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3660:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3661:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3662:     	    push(@files,$file_url.$file);
                   3663:         }
                   3664:     }
                   3665:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3666:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3667:     }
                   3668:     return (\@files);
                   3669: }
1.322     albertel 3670: 
1.269     raeburn  3671: # ----------- Provides number of tries since last reset.
                   3672: sub get_num_tries {
                   3673:     my ($record,$last_reset,$part) = @_;
                   3674:     my $timestamp = '';
                   3675:     my $num_tries = 0;
                   3676:     if ($$record{'version'}) {
                   3677:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3678:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3679:                 $timestamp = $$record{$version.':timestamp'};
                   3680:                 if ($timestamp > $last_reset) {
                   3681:                     $num_tries ++;
                   3682:                 } else {
                   3683:                     last;
                   3684:                 }
                   3685:             }
                   3686:         }
                   3687:     }
                   3688:     return $num_tries;
                   3689: }
                   3690: 
                   3691: # ----------- Determine decrements required in aggregate totals 
                   3692: sub decrement_aggs {
                   3693:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3694:     my %decrement = (
                   3695:                         attempts => 0,
                   3696:                         users => 0,
                   3697:                         correct => 0
                   3698:                     );
                   3699:     $decrement{'attempts'} = $aggtries;
                   3700:     if ($solvedstatus =~ /^correct/) {
                   3701:         $decrement{'correct'} = 1;
                   3702:     }
                   3703:     if ($aggtries == $totaltries) {
                   3704:         $decrement{'users'} = 1;
                   3705:     }
1.524     raeburn  3706:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3707:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3708:     }
                   3709:     return;
                   3710: }
                   3711: 
                   3712: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3713: sub get_last_resets {
1.270     albertel 3714:     my ($symb,$courseid,$partids) =@_;
                   3715:     my %last_resets;
1.269     raeburn  3716:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3717:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3718:     my @keys;
                   3719:     foreach my $part (@{$partids}) {
                   3720: 	push(@keys,"$symb\0$part\0resettime");
                   3721:     }
                   3722:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3723: 				     $cdom,$cname);
                   3724:     foreach my $part (@{$partids}) {
                   3725: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3726:     }
1.270     albertel 3727:     return %last_resets;
1.269     raeburn  3728: }
                   3729: 
1.251     banghart 3730: # ----------- Handles creating versions for portfolio files as answers
                   3731: sub version_portfiles {
1.343     banghart 3732:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3733:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3734:     my @returned_keys;
1.255     banghart 3735:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3736:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3737:     foreach my $key (keys(%$record)) {
1.259     banghart 3738:         my $new_portfiles;
1.263     banghart 3739:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3740:             my @versioned_portfiles;
1.367     albertel 3741:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3742:             foreach my $file (@portfiles) {
1.306     banghart 3743:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3744:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3745: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3746: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3747:):                 my $getpropath = 1;
                   3748:):                 my ($dir_list,$listerror) =
                   3749:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3750:):                                              $stu_name,$getpropath);
                   3751:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3752:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3753:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3754:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3755:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3756:                         [$directory.$new_answer],
1.306     banghart 3757:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3758:                 }
1.252     banghart 3759:             }
1.343     banghart 3760:             $$record{$key} = join(',',@versioned_portfiles);
                   3761:             push(@returned_keys,$key);
1.251     banghart 3762:         }
                   3763:     } 
1.343     banghart 3764:     return (@returned_keys);   
1.305     banghart 3765: }
                   3766: 
1.307     banghart 3767: sub get_next_version {
1.341     banghart 3768:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3769:     my $version;
1.596.2.12.2.  (raeburn 3770:):     if (ref($dir_list) eq 'ARRAY') {
                   3771:):         foreach my $row (@{$dir_list}) {
                   3772:):             my ($file) = split(/\&/,$row,2);
                   3773:):             my ($file_name,$file_version,$file_ext) =
                   3774:): 	        &file_name_version_ext($file);
                   3775:):             if (($file_name eq $answer_name) && 
                   3776:): 	        ($file_ext eq $answer_ext)) {
                   3777:):                 # gets here if filename and extension match, 
                   3778:):                 # regardless of version
1.307     banghart 3779:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3780:):                     # a versioned file is found  so save it for later
                   3781:):                     if ($file_version > $version) {
                   3782:): 		        $version = $file_version;
                   3783:):                     }
1.307     banghart 3784: 	        }
                   3785:             }
                   3786:         }
1.596.2.12.2.  (raeburn 3787:):     }
1.307     banghart 3788:     $version ++;
                   3789:     return($version);
                   3790: }
                   3791: 
1.305     banghart 3792: sub version_selected_portfile {
1.306     banghart 3793:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3794:     my ($answer_name,$answer_ver,$answer_ext) =
                   3795:         &file_name_version_ext($file_name);
                   3796:     my $new_answer;
                   3797:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3798:     if($env{'form.copy'} eq '-1') {
                   3799:         $new_answer = 'problem getting file';
                   3800:     } else {
                   3801:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3802:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3803:                             $stu_name,$domain,'copy',
                   3804: 		        '/portfolio'.$directory.$new_answer);
                   3805:     }    
                   3806:     return ($new_answer);
1.251     banghart 3807: }
                   3808: 
1.304     albertel 3809: sub file_name_version_ext {
                   3810:     my ($file)=@_;
                   3811:     my @file_parts = split(/\./, $file);
                   3812:     my ($name,$version,$ext);
                   3813:     if (@file_parts > 1) {
                   3814: 	$ext=pop(@file_parts);
                   3815: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3816: 	    $version=pop(@file_parts);
                   3817: 	}
                   3818: 	$name=join('.',@file_parts);
                   3819:     } else {
                   3820: 	$name=join('.',@file_parts);
                   3821:     }
                   3822:     return($name,$version,$ext);
                   3823: }
                   3824: 
1.44      ng       3825: #--------------------------------------------------------------------------------------
                   3826: #
                   3827: #-------------------------- Next few routines handles grading by section or whole class
                   3828: #
                   3829: #--- Javascript to handle grading by section or whole class
1.42      ng       3830: sub viewgrades_js {
                   3831:     my ($request) = shift;
                   3832: 
1.539     riegler  3833:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3834:6):     &js_escape(\$alertmsg);
          1(raebur 3835:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3836:    function writePoint(partid,weight,point) {
1.125     ng       3837: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3838: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3839: 	if (point == "textval") {
1.125     ng       3840: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3841: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3842: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3843: 		var resetbox = false;
                   3844: 		for (var i=0; i<radioButton.length; i++) {
                   3845: 		    if (radioButton[i].checked) {
                   3846: 			textbox.value = i;
                   3847: 			resetbox = true;
                   3848: 		    }
                   3849: 		}
                   3850: 		if (!resetbox) {
                   3851: 		    textbox.value = "";
                   3852: 		}
                   3853: 		return;
                   3854: 	    }
1.109     matthew  3855: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3856: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3857: 				   ") greater than the weight for the part. Accept?");
                   3858: 		if (resp == false) {
                   3859: 		    textbox.value = "";
                   3860: 		    return;
                   3861: 		}
                   3862: 	    }
1.42      ng       3863: 	    for (var i=0; i<radioButton.length; i++) {
                   3864: 		radioButton[i].checked=false;
1.109     matthew  3865: 		if (parseFloat(point) == i) {
1.42      ng       3866: 		    radioButton[i].checked=true;
                   3867: 		}
                   3868: 	    }
1.41      ng       3869: 
1.42      ng       3870: 	} else {
1.125     ng       3871: 	    textbox.value = parseFloat(point);
1.42      ng       3872: 	}
1.41      ng       3873: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3874: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3875: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3876: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3877: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3878: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3879: 	    if (saveval != "correct") {
                   3880: 		scorename.value = point;
1.43      ng       3881: 		if (selname[0].selected != true) {
                   3882: 		    selname[0].selected = true;
                   3883: 		}
1.42      ng       3884: 	    }
                   3885: 	}
1.125     ng       3886: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3887:     }
                   3888: 
                   3889:     function writeRadText(partid,weight) {
1.125     ng       3890: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3891: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3892:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3893: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3894: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3895: 	    for (var i=0; i<radioButton.length; i++) {
                   3896: 		radioButton[i].checked=false;
                   3897: 
                   3898: 	    }
                   3899: 	    textbox.value = "";
                   3900: 
                   3901: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3902: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3903: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3904: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3905: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3906: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3907: 		if ((saveval != "correct") || override) {
1.42      ng       3908: 		    scorename.value = "";
1.125     ng       3909: 		    if (selval[1].selected) {
                   3910: 			selname[1].selected = true;
                   3911: 		    } else {
                   3912: 			selname[2].selected = true;
                   3913: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3914: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3915: 		    }
1.42      ng       3916: 		}
                   3917: 	    }
1.43      ng       3918: 	} else {
                   3919: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3920: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3921: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3922: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3923: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3924: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3925: 		if ((saveval != "correct") || override) {
1.125     ng       3926: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3927: 		    selname[0].selected = true;
                   3928: 		}
                   3929: 	    }
                   3930: 	}	    
1.42      ng       3931:     }
                   3932: 
                   3933:     function changeSelect(partid,user) {
1.125     ng       3934: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3935: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3936: 	var point  = textbox.value;
1.125     ng       3937: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3938: 
1.109     matthew  3939: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3940: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3941: 	    textbox.value = "";
                   3942: 	    return;
                   3943: 	}
1.109     matthew  3944: 	if (parseFloat(point) > parseFloat(weight)) {
                   3945: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3946: 			       ") greater than the weight of the part. Accept?");
                   3947: 	    if (resp == false) {
                   3948: 		textbox.value = "";
                   3949: 		return;
                   3950: 	    }
                   3951: 	}
1.42      ng       3952: 	selval[0].selected = true;
                   3953:     }
                   3954: 
                   3955:     function changeOneScore(partid,user) {
1.125     ng       3956: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3957: 	if (selval[1].selected || selval[2].selected) {
                   3958: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3959: 	    if (selval[2].selected) {
                   3960: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3961: 	    }
1.269     raeburn  3962:         }
1.42      ng       3963:     }
                   3964: 
                   3965:     function resetEntry(numpart) {
                   3966: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3967: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3968: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3969: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3970: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3971: 	    for (var i=0; i<radioButton.length; i++) {
                   3972: 		radioButton[i].checked=false;
                   3973: 
                   3974: 	    }
                   3975: 	    textbox.value = "";
                   3976: 	    selval[0].selected = true;
                   3977: 
                   3978: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3979: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3980: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3981: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3982: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3983: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3984: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3985: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3986: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3987: 		if (saveselval == "excused") {
1.43      ng       3988: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3989: 		} else {
1.43      ng       3990: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3991: 		}
                   3992: 	    }
1.41      ng       3993: 	}
1.42      ng       3994:     }
                   3995: 
1.41      ng       3996: VIEWJAVASCRIPT
1.42      ng       3997: }
                   3998: 
1.44      ng       3999: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       4000: sub viewgrades {
1.596.2.12.2.  1(raebur 4001:0):     my ($request,$symb) = @_;
1.42      ng       4002:     &viewgrades_js($request);
1.41      ng       4003: 
1.168     albertel 4004:     #need to make sure we have the correct data for later EXT calls, 
                   4005:     #thus invalidate the cache
                   4006:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4007:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4008:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4009:     &Apache::lonnet::clear_EXT_cache_status();
                   4010: 
1.398     albertel 4011:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       4012: 
                   4013:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 4014:     $result.=&jscriptNform($symb);
1.41      ng       4015: 
1.44      ng       4016:     #beginning of class grading form
1.442     banghart 4017:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       4018:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 4019: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       4020: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 4021: 	&build_section_inputs().
1.442     banghart 4022: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       4023: 
1.596.2.12.2.  7(raebur 4024:6):     #retrieve selected groups
                   4025:6):     my (@groups,$group_display);
          8(raebur 4026:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 4027:6):     if (grep(/^all$/,@groups)) {
                   4028:6):         @groups = ('all');
                   4029:6):     } elsif (grep(/^none$/,@groups)) {
                   4030:6):         @groups = ('none');
                   4031:6):     } elsif (@groups > 0) {
                   4032:6):         $group_display = join(', ',@groups);
                   4033:6):     }
                   4034:6): 
                   4035:6):     my ($common_header,$specific_header,@sections,$section_display);
          6(raebur 4036:1):     if ($env{'request.course.sec'} ne '') {
                   4037:1):         @sections = ($env{'request.course.sec'});
                   4038:1):     } else {
                   4039:1):         @sections = &Apache::loncommon::get_env_multiple('form.section');
                   4040:1):     }
                   4041:1): 
                   4042:1): # Check if Save button should be usable
                   4043:1):     my $disabled = ' disabled="disabled"';
                   4044:1):     if ($perm{'mgr'}) {
                   4045:1):         if (grep(/^all$/,@sections)) {
                   4046:1):             undef($disabled);
                   4047:1):         } else {
                   4048:1):             foreach my $sec (@sections) {
                   4049:1):                 if (&canmodify($sec)) {
                   4050:1):                     undef($disabled);
                   4051:1):                     last;
                   4052:1):                 }
                   4053:1):             }
                   4054:1):         }
                   4055:1):     }
          7(raebur 4056:6):     if (grep(/^all$/,@sections)) {
                   4057:6):         @sections = ('all');
                   4058:6):         if ($group_display) {
                   4059:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4060:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4061:6):         } elsif (grep(/^none$/,@groups)) {
                   4062:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4063:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4064:6):         } else {
                   4065:6):             $common_header = &mt('Assign Common Grade to Class');
                   4066:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4067:6):         }
                   4068:6):     } elsif (grep(/^none$/,@sections)) {
                   4069:6):         @sections = ('none');
                   4070:6):         if ($group_display) {
                   4071:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4072:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4073:6):         } elsif (grep(/^none$/,@groups)) {
                   4074:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4075:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4076:6):         } else {
                   4077:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4078:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4079:6):         }
                   4080:6):     } else {
                   4081:6):         $section_display = join (", ",@sections);
                   4082:6):         if ($group_display) {
                   4083:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4084:6):                                  $section_display,$group_display);
                   4085:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4086:6):                                    $section_display,$group_display);
                   4087:6):         } elsif (grep(/^none$/,@groups)) {
                   4088:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4089:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4090:6):         } else {
                   4091:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4092:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4093:6):         }
1.52      albertel 4094:     }
1.596.2.12.2.  7(raebur 4095:6):     my %submit_types = &substatus_options();
                   4096:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4097:6): 
                   4098:6):     if ($env{'form.submitonly'} eq 'all') {
                   4099:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4100:6):     } else {
                   4101:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   4102:6):     }
                   4103:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4104:     #radio buttons/text box for assigning points for a section or class.
                   4105:     #handles different parts of a problem
1.582     raeburn  4106:     my $res_error;
                   4107:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4108:     if ($res_error) {
                   4109:         return &navmap_errormsg();
                   4110:     }
1.42      ng       4111:     my %weight = ();
                   4112:     my $ctsparts = 0;
1.45      ng       4113:     my %seen = ();
1.375     albertel 4114:     my @part_response_id = &flatten_responseType($responseType);
                   4115:     foreach my $part_response_id (@part_response_id) {
                   4116:     	my ($partid,$respid) = @{ $part_response_id };
                   4117: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4118: 	next if $seen{$partid};
                   4119: 	$seen{$partid}++;
1.42      ng       4120: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4121: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4122: 
1.324     albertel 4123: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4124: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4125: 	my $ctr = 0;
1.42      ng       4126: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4127: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4128: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4129: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4130: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4131: 	    $ctr++;
                   4132: 	}
1.485     albertel 4133: 	$radio.='</tr></table>';
                   4134: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4135: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4136: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4137: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4138:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4139:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4140:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4141: 		$weight{$partid}.')"> '.
1.401     albertel 4142: 	    '<option selected="selected"> </option>'.
1.485     albertel 4143: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4144: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4145: 	    '</select></td>'.
                   4146:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4147: 	$line.='<input type="hidden" name="partid_'.
                   4148: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4149: 	$line.='<input type="hidden" name="weight_'.
                   4150: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4151: 
                   4152: 	$result.=
                   4153: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4154: 	    '<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 4155: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4156: 	$ctsparts++;
1.41      ng       4157:     }
1.474     albertel 4158:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4159: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4160:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4161: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4162: 
1.44      ng       4163:     #table listing all the students in a section/class
                   4164:     #header of table
1.596.2.12.2.  7(raebur 4165:6):     if ($env{'form.submitonly'} eq 'all') { 
                   4166:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4167:6):     } else {
                   4168:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   4169:6):     }
                   4170:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4171: 	      &Apache::loncommon::start_data_table_header_row().
                   4172: 	      '<th>'.&mt('No.').'</th>'.
                   4173: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4174:     my $partserror;
                   4175:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4176:     if ($partserror) {
                   4177:         return &navmap_errormsg();
                   4178:     }
1.324     albertel 4179:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4180:     my @partids = ();
1.41      ng       4181:     foreach my $part (@parts) {
                   4182: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  4183:         my $narrowtext = &mt('Tries');
                   4184: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       4185: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 4186: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4187:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4188:0): #
                   4189:0): # FIXME: Looks like $display looks at English text
                   4190:0): #
1.324     albertel 4191: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4192: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4193: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4194:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4195:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4196: 	    next;
1.485     albertel 4197: 	    
1.207     albertel 4198: 	} else {
1.485     albertel 4199: 	    if ($display =~ /Problem Status/) {
                   4200: 		my $grade_status_mt = &mt('Grade Status');
                   4201: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4202: 	    }
                   4203: 	    my $part_mt = &mt('Part:');
                   4204: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4205: 	}
1.485     albertel 4206: 
1.474     albertel 4207: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4208:     }
1.474     albertel 4209:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4210: 
1.270     albertel 4211:     my %last_resets = 
                   4212: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4213: 
1.41      ng       4214:     #get info for each student
1.44      ng       4215:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4216:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4217:     my $ctr = 0;
1.294     albertel 4218:     foreach (sort 
                   4219: 	     {
                   4220: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4221: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4222: 		 }
                   4223: 		 return $a cmp $b;
                   4224: 	     } (keys(%$fullname))) {
1.324     albertel 4225: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 4226:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       4227:     }
1.474     albertel 4228:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4229:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.596.2.12.2.  6(raebur 4230:1):     $result.='<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   4231: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4232:6):     if ($ctr == 0) {
1.442     banghart 4233:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4234:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4235:6):                 '<span class="LC_warning">';
                   4236:6):         if ($env{'form.submitonly'} eq 'all') {
                   4237:6):             if (grep(/^all$/,@sections)) {
                   4238:6):                 if (grep(/^all$/,@groups)) {
                   4239:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4240:6):                                    $stu_status);
                   4241:6):                 } elsif (grep(/^none$/,@groups)) {
                   4242:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4243:6):                                    $stu_status);
                   4244:6):                 } else {
                   4245:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4246:6):                                    $group_display,$stu_status);
                   4247:6):                 }
                   4248:6):             } elsif (grep(/^none$/,@sections)) {
                   4249:6):                 if (grep(/^all$/,@groups)) {
                   4250:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4251:6):                                    $stu_status);
                   4252:6):                 } elsif (grep(/^none$/,@groups)) {
                   4253:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4254:6):                                    $stu_status);
                   4255:6):                 } else {
                   4256:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4257:6):                                    $group_display,$stu_status);
                   4258:6):                 }
                   4259:6):             } else {
                   4260:6):                 if (grep(/^all$/,@groups)) {
                   4261:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4262:6):                                    $section_display,$stu_status);
                   4263:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4264:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4265:6):                                    $section_display,$stu_status);
                   4266:6):                 } else {
                   4267:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4268:6):                                    $section_display,$group_display,$stu_status);
                   4269:6):                 }
                   4270:6):             }
                   4271:6):         } else {
                   4272:6):             if (grep(/^all$/,@sections)) {
                   4273:6):                 if (grep(/^all$/,@groups)) {
                   4274:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4275:6):                                    $stu_status,$submission_status);
                   4276:6):                 } elsif (grep(/^none$/,@groups)) {
                   4277:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4278:6):                                    $stu_status,$submission_status);
                   4279:6):                 } else {
                   4280:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4281:6):                                    $group_display,$stu_status,$submission_status);
                   4282:6):                 }
                   4283:6):             } elsif (grep(/^none$/,@sections)) {
                   4284:6):                 if (grep(/^all$/,@groups)) {
                   4285:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4286:6):                                    $stu_status,$submission_status);
                   4287:6):                 } elsif (grep(/^none$/,@groups)) {
                   4288: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.',
                   4289:6):                                    $stu_status,$submission_status);
                   4290:6):                 } else {
                   4291: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.',
                   4292:6):                                    $group_display,$stu_status,$submission_status);
                   4293:6):                 }
                   4294:6):             } else {
                   4295:6):                 if (grep(/^all$/,@groups)) {
                   4296:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4297:6):                                    $section_display,$stu_status,$submission_status);
                   4298:6):                 } elsif (grep(/^none$/,@groups)) {
                   4299: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.',
                   4300:6):                                    $section_display,$stu_status,$submission_status);
                   4301:6):                 } else {
                   4302: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.',
                   4303:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4304:6):                 }
                   4305:6):             }
                   4306:6): 	}
                   4307:6): 	$result .= '</span><br />';
1.96      albertel 4308:     }
1.41      ng       4309:     return $result;
                   4310: }
                   4311: 
1.596.2.12.2.  7(raebur 4312:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4313: sub viewstudentgrade {
1.324     albertel 4314:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4315:     my ($uname,$udom) = split(/:/,$student);
                   4316:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4317:6):     my $submitonly = $env{'form.submitonly'};
                   4318:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4319:6):         my %partstatus = ();
                   4320:6):         if (ref($parts) eq 'ARRAY') {
                   4321:6):             foreach my $apart (@{$parts}) {
                   4322:6):                 my ($part,$type) = &split_part_type($apart);
                   4323:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4324:6):                 $status = 'nothing' if ($status eq '');
                   4325:6):                 $partstatus{$part}      = $status;
                   4326:6):                 my $subkey = "resource.$part.submitted_by";
                   4327:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4328:6):             }
                   4329:6):             my $submitted = 0;
                   4330:6):             my $graded = 0;
                   4331:6):             my $incorrect = 0;
                   4332:6):             foreach my $key (keys(%partstatus)) {
                   4333:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4334:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4335:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4336:6): 
                   4337:6):                 my $partid = (split(/\./,$key))[1];
                   4338:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4339:6):                     $submitted = 0;
                   4340:6):                 }
                   4341:6):             }
                   4342:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4343:6):                                        $submitonly eq 'incorrect' ||
                   4344:6):                                        $submitonly eq 'graded'));
                   4345:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4346:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4347:6):         }
                   4348:6):     }
                   4349:6):     if ($submitonly eq 'queued') {
                   4350:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4351:6):         my %queue_status =
                   4352:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4353:6):                                                     $udom,$uname);
                   4354:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4355:6):     }
                   4356:6):     $$ctr++;
                   4357:6):     my %aggregates = ();
1.474     albertel 4358:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4359:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4360:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4361: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4362: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4363: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4364:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4365:     foreach my $apart (@$parts) {
                   4366: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4367: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4368:         $result.='<td align="center">';
1.269     raeburn  4369:         my ($aggtries,$totaltries);
                   4370:         unless (exists($aggregates{$part})) {
1.270     albertel 4371: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4372: 
                   4373: 	    $aggtries = $totaltries;
1.269     raeburn  4374:             if ($$last_resets{$part}) {  
1.270     albertel 4375:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4376: 					   $part);
                   4377:             }
1.269     raeburn  4378:             $result.='<input type="hidden" name="'.
                   4379:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4380:             $result.='<input type="hidden" name="'.
                   4381:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4382:             $aggregates{$part} = 1;
                   4383:         }
1.41      ng       4384: 	if ($type eq 'awarded') {
1.320     albertel 4385: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4386: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4387: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4388: 	    $result.='<input type="text" name="'.
1.89      albertel 4389: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4390:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4391: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4392: 	} elsif ($type eq 'solved') {
                   4393: 	    my ($status,$foo)=split(/_/,$score,2);
                   4394: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4395: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4396: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4397: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4398: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4399:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4400: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4401: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4402: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4403: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4404: 	} else {
                   4405: 	    $result.='<input type="hidden" name="'.
                   4406: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4407: 		    "\n";
1.233     albertel 4408: 	    $result.='<input type="text" name="'.
1.122     ng       4409: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4410: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4411: 	}
                   4412:     }
1.474     albertel 4413:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4414:     return $result;
1.38      ng       4415: }
                   4416: 
1.44      ng       4417: #--- change scores for all the students in a section/class
                   4418: #    record does not get update if unchanged
1.38      ng       4419: sub editgrades {
1.596.2.12.2.  1(raebur 4420:0):     my ($request,$symb) = @_;
1.41      ng       4421: 
1.433     banghart 4422:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4423:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4424:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4425: 
1.477     albertel 4426:     my $result= &Apache::loncommon::start_data_table().
                   4427: 	&Apache::loncommon::start_data_table_header_row().
                   4428: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4429: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4430:     my %scoreptr = (
                   4431: 		    'correct'  =>'correct_by_override',
                   4432: 		    'incorrect'=>'incorrect_by_override',
                   4433: 		    'excused'  =>'excused',
                   4434: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4435:                     'credited' =>'credit_attempted',
1.43      ng       4436: 		    'nothing'  => '',
                   4437: 		    );
1.257     albertel 4438:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4439: 
1.44      ng       4440:     my (@partid);
                   4441:     my %weight = ();
1.54      albertel 4442:     my %columns = ();
1.44      ng       4443:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4444: 
1.582     raeburn  4445:     my $partserror;
                   4446:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4447:     if ($partserror) {
                   4448:         return &navmap_errormsg();
                   4449:     }
1.54      albertel 4450:     my $header;
1.257     albertel 4451:     while ($ctr < $env{'form.totalparts'}) {
                   4452: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4453: 	push(@partid,$partid);
1.257     albertel 4454: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4455: 	$ctr++;
1.54      albertel 4456:     }
1.324     albertel 4457:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4458:8):     my $totcolspan = 0;
1.54      albertel 4459:     foreach my $partid (@partid) {
1.478     albertel 4460: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4461: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4462: 	$columns{$partid}=2;
                   4463: 	foreach my $stores (@parts) {
                   4464: 	    my ($part,$type) = &split_part_type($stores);
                   4465: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4466: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4467: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4468: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4469:             my $narrowtext = &mt('Tries');
                   4470: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4471: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4472: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4473: 	    $columns{$partid}+=2;
                   4474: 	}
1.596.2.12.2.  2(raebur 4475:8):         $totcolspan += $columns{$partid};
1.54      albertel 4476:     }
                   4477:     foreach my $partid (@partid) {
1.324     albertel 4478: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4479: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4480: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4481: 	    '</th>';
1.54      albertel 4482: 
1.44      ng       4483:     }
1.477     albertel 4484:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4485: 	&Apache::loncommon::start_data_table_header_row().
                   4486: 	$header.
                   4487: 	&Apache::loncommon::end_data_table_header_row();
                   4488:     my @noupdate;
1.126     ng       4489:     my ($updateCtr,$noupdateCtr) = (1,1);
1.596.2.12.2.  8(raebur 4490:1):     my ($got_types,%queueable);
1.257     albertel 4491:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4492: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4493: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4494: 	my %newrecord;
                   4495: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4496:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4497:8):         my $canmodify = &canmodify($usec);
                   4498:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4499:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4500:8):         if (!$canmodify) {
                   4501:8):             push(@noupdate,
                   4502:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4503:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4504:8):             next;
                   4505:8):         }
1.269     raeburn  4506:         my %aggregate = ();
                   4507:         my $aggregateflag = 0;
1.281     albertel 4508: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4509: 	foreach (@partid) {
1.257     albertel 4510: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4511: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4512: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4513: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4514: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4515: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4516: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4517: 	    my $score;
                   4518: 	    if ($partial eq '') {
1.257     albertel 4519: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4520: 	    } elsif ($partial > 0) {
                   4521: 		$score = 'correct_by_override';
                   4522: 	    } elsif ($partial == 0) {
                   4523: 		$score = 'incorrect_by_override';
                   4524: 	    }
1.257     albertel 4525: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4526: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4527: 
1.292     albertel 4528: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4529: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4530: 	    if ($dropMenu eq 'reset status' &&
                   4531: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4532: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4533: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4534: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4535: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4536: 		$updateflag = 1;
1.269     raeburn  4537:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4538:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4539:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4540:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4541:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4542:                     $aggregateflag = 1;
                   4543:                 }
1.139     albertel 4544: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4545: 		$updateflag = 1;
                   4546: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4547: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4548: 		$rec_update++;
1.125     ng       4549: 	    }
                   4550: 
1.93      albertel 4551: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4552: 		'<td align="center">'.$awarded.
                   4553: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4554: 
1.54      albertel 4555: 
                   4556: 	    my $partid=$_;
                   4557: 	    foreach my $stores (@parts) {
                   4558: 		my ($part,$type) = &split_part_type($stores);
                   4559: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4560: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4561: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4562: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4563: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4564: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4565: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4566: 		    $updateflag=1;
                   4567: 		}
1.93      albertel 4568: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4569: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4570: 	    }
1.44      ng       4571: 	}
1.477     albertel 4572: 	$line.="\n";
1.301     albertel 4573: 
                   4574: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4575: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4576: 
1.44      ng       4577: 	if ($updateflag) {
                   4578: 	    $count++;
1.257     albertel 4579: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4580: 				    $udom,$uname);
1.301     albertel 4581: 
                   4582: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4583: 					      $cnum,$udom,$uname)) {
                   4584: 		# need to figure out if should be in queue.
                   4585: 		my %record =  
                   4586: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4587: 					     $udom,$uname);
                   4588: 		my $all_graded = 1;
                   4589: 		my $none_graded = 1;
1.596.2.12.2.  8(raebur 4590:1):                 unless ($got_types) {
                   4591:1):                     my $error;
                   4592:1):                     my ($plist,$handgrd,$resptype) = &response_type($symb,\$error);
                   4593:1):                     unless ($error) {
                   4594:1):                         foreach my $part (@parts) {
                   4595:1):                             if (ref($resptype->{$part}) eq 'HASH') {
                   4596:1):                                 foreach my $id (keys(%{$resptype->{$part}})) {
                   4597:1):                                     if (($resptype->{$part}->{$id} eq 'essay') ||
                   4598:1):                                         (lc($handgrd->{$part.'_'.$id}) eq 'yes')) {
                   4599:1):                                         $queueable{$part} = 1;
                   4600:1):                                         last;
                   4601:1):                                     }
                   4602:1):                                 }
                   4603:1):                             }
                   4604:1):                         }
                   4605:1):                     }
                   4606:1):                     $got_types = 1;
                   4607:1):                 }
1.301     albertel 4608: 		foreach my $part (@parts) {
1.596.2.12.2.  8(raebur 4609:1):                     if ($queueable{$part}) {
                   4610:1): 		        if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4611:1): 			    $all_graded = 0;
                   4612:1): 		        } else {
                   4613:1): 			    $none_graded = 0;
                   4614:1): 		        }
                   4615:1):                     }
1.301     albertel 4616: 		}
                   4617: 
                   4618: 		if ($all_graded || $none_graded) {
                   4619: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4620: 							   $symb,$cdom,$cnum,
                   4621: 							   $udom,$uname);
                   4622: 		}
                   4623: 	    }
                   4624: 
1.477     albertel 4625: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4626: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4627: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4628: 	    $updateCtr++;
1.93      albertel 4629: 	} else {
1.477     albertel 4630: 	    push(@noupdate,
                   4631: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4632: 	    $noupdateCtr++;
1.44      ng       4633: 	}
1.269     raeburn  4634:         if ($aggregateflag) {
                   4635:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4636: 				  $cdom,$cnum);
1.269     raeburn  4637:         }
1.93      albertel 4638:     }
1.477     albertel 4639:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4640:8):         my $numcols=$totcolspan+2;
1.477     albertel 4641: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4642: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4643: 	    &mt('No Changes Occurred For the Students Below').
                   4644: 	    '</td>'.
1.477     albertel 4645: 	    &Apache::loncommon::end_data_table_row();
                   4646: 	foreach my $line (@noupdate) {
                   4647: 	    $result.=
                   4648: 		&Apache::loncommon::start_data_table_row().
                   4649: 		$line.
                   4650: 		&Apache::loncommon::end_data_table_row();
                   4651: 	}
1.44      ng       4652:     }
1.596.2.12.2.  1(raebur 4653:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4654:     my $msg = '<p><b>'.
                   4655: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4656: 	    $rec_update,$count).'</b><br />'.
                   4657: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4658: 	'</b></p>';
1.44      ng       4659:     return $title.$msg.$result;
1.5       albertel 4660: }
1.54      albertel 4661: 
                   4662: sub split_part_type {
                   4663:     my ($partstr) = @_;
                   4664:     my ($temp,@allparts)=split(/_/,$partstr);
                   4665:     my $type=pop(@allparts);
1.439     albertel 4666:     my $part=join('_',@allparts);
1.54      albertel 4667:     return ($part,$type);
                   4668: }
                   4669: 
1.44      ng       4670: #------------- end of section for handling grading by section/class ---------
                   4671: #
                   4672: #----------------------------------------------------------------------------
                   4673: 
1.5       albertel 4674: 
1.44      ng       4675: #----------------------------------------------------------------------------
                   4676: #
                   4677: #-------------------------- Next few routines handles grading by csv upload
                   4678: #
                   4679: #--- Javascript to handle csv upload
1.27      albertel 4680: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4681:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4682:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4683:6):   &js_escape(\$error1);
                   4684:6):   &js_escape(\$error2);
1.27      albertel 4685:   return(<<ENDPICK);
                   4686:   function verify(vf) {
                   4687:     var foundsomething=0;
                   4688:     var founduname=0;
1.243     albertel 4689:     var foundID=0;
1.27      albertel 4690:     for (i=0;i<=vf.nfields.value;i++) {
                   4691:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4692:       if (i==0 && tw!=0) { foundID=1; }
                   4693:       if (i==1 && tw!=0) { founduname=1; }
                   4694:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4695:     }
1.246     albertel 4696:     if (founduname==0 && foundID==0) {
                   4697: 	alert('$error1');
                   4698: 	return;
1.27      albertel 4699:     }
                   4700:     if (foundsomething==0) {
1.246     albertel 4701: 	alert('$error2');
                   4702: 	return;
1.27      albertel 4703:     }
                   4704:     vf.submit();
                   4705:   }
                   4706:   function flip(vf,tf) {
                   4707:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4708:     var i;
                   4709:     for (i=0;i<=vf.nfields.value;i++) {
                   4710:       //can not pick the same destination field for both name and domain
                   4711:       if (((i ==0)||(i ==1)) && 
                   4712:           ((tf==0)||(tf==1)) && 
                   4713:           (i!=tf) &&
                   4714:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4715:         eval('vf.f'+i+'.selectedIndex=0;')
                   4716:       }
                   4717:     }
                   4718:   }
                   4719: ENDPICK
                   4720: }
                   4721: 
                   4722: sub csvupload_javascript_forward_associate {
1.573     bisitz   4723:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4724:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4725:6):   &js_escape(\$error1);
                   4726:6):   &js_escape(\$error2);
1.27      albertel 4727:   return(<<ENDPICK);
                   4728:   function verify(vf) {
                   4729:     var foundsomething=0;
                   4730:     var founduname=0;
1.243     albertel 4731:     var foundID=0;
1.27      albertel 4732:     for (i=0;i<=vf.nfields.value;i++) {
                   4733:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4734:       if (tw==1) { foundID=1; }
                   4735:       if (tw==2) { founduname=1; }
                   4736:       if (tw>3) { foundsomething=1; }
1.27      albertel 4737:     }
1.246     albertel 4738:     if (founduname==0 && foundID==0) {
                   4739: 	alert('$error1');
                   4740: 	return;
1.27      albertel 4741:     }
                   4742:     if (foundsomething==0) {
1.246     albertel 4743: 	alert('$error2');
                   4744: 	return;
1.27      albertel 4745:     }
                   4746:     vf.submit();
                   4747:   }
                   4748:   function flip(vf,tf) {
                   4749:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4750:     var i;
                   4751:     //can not pick the same destination field twice
                   4752:     for (i=0;i<=vf.nfields.value;i++) {
                   4753:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4754:         eval('vf.f'+i+'.selectedIndex=0;')
                   4755:       }
                   4756:     }
                   4757:   }
                   4758: ENDPICK
                   4759: }
                   4760: 
1.26      albertel 4761: sub csvuploadmap_header {
1.324     albertel 4762:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4763:     my $javascript;
1.257     albertel 4764:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4765: 	$javascript=&csvupload_javascript_reverse_associate();
                   4766:     } else {
                   4767: 	$javascript=&csvupload_javascript_forward_associate();
                   4768:     }
1.45      ng       4769: 
1.257     albertel 4770:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4771:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4772:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4773:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4774:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4775:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4776:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4777:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4778:0): <br />
                   4779:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4780: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4781: <input type="hidden" name="associate"  value="" />
                   4782: <input type="hidden" name="phase"      value="three" />
                   4783: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4784: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4785: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4786: <input type="hidden" name="upfile_associate" 
1.257     albertel 4787:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4788: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4789: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4790: <hr />
                   4791: ENDPICK
1.596.2.12.2.  1(raebur 4792:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4793:     return '';
1.26      albertel 4794: 
                   4795: }
                   4796: 
                   4797: sub csvupload_fields {
1.582     raeburn  4798:     my ($symb,$errorref) = @_;
                   4799:     my (@parts) = &getpartlist($symb,$errorref);
                   4800:     if (ref($errorref)) {
                   4801:         if ($$errorref) {
                   4802:             return;
                   4803:         }
                   4804:     }
                   4805: 
1.556     weissno  4806:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4807: 		['username','Student Username'],
                   4808: 		['domain','Student Domain']);
1.324     albertel 4809:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4810:     foreach my $part (sort(@parts)) {
                   4811: 	my @datum;
                   4812: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4813: 	my $name=$part;
                   4814: 	if  (!$display) { $display = $name; }
                   4815: 	@datum=($name,$display);
1.244     albertel 4816: 	if ($name=~/^stores_(.*)_awarded/) {
                   4817: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4818: 	}
1.41      ng       4819: 	push(@fields,\@datum);
                   4820:     }
                   4821:     return (@fields);
1.26      albertel 4822: }
                   4823: 
                   4824: sub csvuploadmap_footer {
1.41      ng       4825:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4826:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4827:     $request->print(<<ENDPICK);
1.26      albertel 4828: </table>
                   4829: <input type="hidden" name="nfields" value="$i" />
                   4830: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4831:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4832: </form>
                   4833: ENDPICK
                   4834: }
                   4835: 
1.283     albertel 4836: sub checkforfile_js {
1.539     riegler  4837:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4838:6):     &js_escape(\$alertmsg);
          1(raebur 4839:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4840:     function checkUpload(formname) {
                   4841: 	if (formname.upfile.value == "") {
1.539     riegler  4842: 	    alert("$alertmsg");
1.86      ng       4843: 	    return false;
                   4844: 	}
                   4845: 	formname.submit();
                   4846:     }
                   4847: CSVFORMJS
1.283     albertel 4848:     return $result;
                   4849: }
                   4850: 
                   4851: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4852:0):     my ($request,$symb) = @_;
1.283     albertel 4853:     if (!$symb) {return '';}
                   4854:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4855:0):     $result.=&Apache::loncommon::start_data_table().
                   4856:0):              &Apache::loncommon::start_data_table_header_row().
                   4857:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4858:0):              &Apache::loncommon::end_data_table_header_row().
                   4859:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4860:     my $upload=&mt("Upload Scores");
1.86      ng       4861:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4862:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4863:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4864:     $result.=<<ENDUPFORM;
1.106     albertel 4865: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4866: <input type="hidden" name="symb" value="$symb" />
                   4867: <input type="hidden" name="command" value="csvuploadmap" />
                   4868: $upfile_select
1.589     bisitz   4869: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4870: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4871: </form>
                   4872: ENDUPFORM
1.370     www      4873:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4874:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4875:0):             '</td>'.
                   4876:0):             &Apache::loncommon::end_data_table_row().
                   4877:0):             &Apache::loncommon::end_data_table();
1.86      ng       4878:     return $result;
                   4879: }
                   4880: 
                   4881: 
1.26      albertel 4882: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4883:0):     my ($request,$symb) = @_;
1.41      ng       4884:     if (!$symb) {return '';}
1.72      ng       4885: 
1.41      ng       4886:     my $datatoken;
1.257     albertel 4887:     if (!$env{'form.datatoken'}) {
1.41      ng       4888: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4889:     } else {
1.596.2.12.2.  3(raebur 4890:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4891:8):         if ($datatoken ne '') { 
                   4892:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4893:8):         }
1.26      albertel 4894:     }
1.41      ng       4895:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4896:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4897:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4898:     my ($i,$keyfields);
                   4899:     if (@records) {
1.582     raeburn  4900:         my $fieldserror;
                   4901: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4902:         if ($fieldserror) {
                   4903:             $request->print(&navmap_errormsg());
                   4904:             return;
                   4905:         }
1.257     albertel 4906: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4907: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4908: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4909: 							  \@fields);
                   4910: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4911: 	    chop($keyfields);
                   4912: 	} else {
                   4913: 	    unshift(@fields,['none','']);
                   4914: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4915: 							    \@fields);
1.311     banghart 4916:             foreach my $rec (@records) {
                   4917:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4918:                 if (%temp) {
                   4919:                     $keyfields=join(',',sort(keys(%temp)));
                   4920:                     last;
                   4921:                 }
                   4922:             }
1.41      ng       4923: 	}
                   4924:     }
                   4925:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4926: 
1.41      ng       4927:     return '';
1.27      albertel 4928: }
                   4929: 
1.246     albertel 4930: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 4931:0):     my ($request,$symb)= @_;
                   4932:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 4933:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4934:     my $ignore=&mt('Ignore First Line');
                   4935:     $request->print(<<ENDPICK);
                   4936: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4937: <input type="hidden" name="command"    value="csvuploadassign" />
                   4938: <p>
                   4939: <label>
                   4940:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 4941:0):    $overwrite
1.246     albertel 4942: </label>
                   4943: </p>
                   4944: ENDPICK
                   4945:     my %fields=&get_fields();
                   4946:     if (!defined($fields{'domain'})) {
1.257     albertel 4947: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 4948:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4949:     }
1.257     albertel 4950:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4951: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4952: 	my $cleankey=$1;
                   4953: 	if ($cleankey eq 'command') { next; }
                   4954: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4955: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4956:     }
                   4957:     # FIXME do a check for any duplicated user ids...
                   4958:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4959:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4960: <hr /></form>'."\n");
1.246     albertel 4961:     return '';
                   4962: }
                   4963: 
                   4964: sub get_fields {
                   4965:     my %fields;
1.257     albertel 4966:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4967:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4968: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4969: 	    if ($env{'form.f'.$i} ne 'none') {
                   4970: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4971: 	    }
                   4972: 	} else {
1.257     albertel 4973: 	    if ($env{'form.f'.$i} ne 'none') {
                   4974: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4975: 	    }
                   4976: 	}
1.27      albertel 4977:     }
1.246     albertel 4978:     return %fields;
                   4979: }
                   4980: 
                   4981: sub csvuploadassign {
1.596.2.12.2.  1(raebur 4982:0):     my ($request,$symb) = @_;
1.246     albertel 4983:     if (!$symb) {return '';}
1.345     bowersj2 4984:     my $error_msg = '';
1.596.2.12.2.  3(raebur 4985:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4986:8):     if ($datatoken ne '') {
                   4987:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4988:8):     }
1.246     albertel 4989:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4990:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4991:     my %fields=&get_fields();
1.257     albertel 4992:     my $courseid=$env{'request.course.id'};
1.97      albertel 4993:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4994:     my @notallowed;
1.41      ng       4995:     my @skipped;
1.596.2.4  raeburn  4996:     my @warnings;
1.41      ng       4997:     my $countdone=0;
                   4998:     foreach my $grade (@gradedata) {
                   4999: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 5000: 	my $domain;
                   5001: 	if ($entries{$fields{'domain'}}) {
                   5002: 	    $domain=$entries{$fields{'domain'}};
                   5003: 	} else {
1.257     albertel 5004: 	    $domain=$env{'form.default_domain'};
1.246     albertel 5005: 	}
1.243     albertel 5006: 	$domain=~s/\s//g;
1.41      ng       5007: 	my $username=$entries{$fields{'username'}};
1.160     albertel 5008: 	$username=~s/\s//g;
1.243     albertel 5009: 	if (!$username) {
                   5010: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 5011: 	    $id=~s/\s//g;
1.243     albertel 5012: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   5013: 	    $username=$ids{$id};
                   5014: 	}
1.41      ng       5015: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 5016: 	    my $id=$entries{$fields{'ID'}};
                   5017: 	    $id=~s/\s//g;
                   5018: 	    if ($id) {
                   5019: 		push(@skipped,"$id:$domain");
                   5020: 	    } else {
                   5021: 		push(@skipped,"$username:$domain");
                   5022: 	    }
1.41      ng       5023: 	    next;
                   5024: 	}
1.108     albertel 5025: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 5026: 	if (!&canmodify($usec)) {
                   5027: 	    push(@notallowed,"$username:$domain");
                   5028: 	    next;
                   5029: 	}
1.244     albertel 5030: 	my %points;
1.41      ng       5031: 	my %grades;
                   5032: 	foreach my $dest (keys(%fields)) {
1.244     albertel 5033: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   5034: 		$dest eq 'domain') { next; }
                   5035: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   5036: 	    if ($dest=~/stores_(.*)_points/) {
                   5037: 		my $part=$1;
                   5038: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   5039: 					      $symb,$domain,$username);
1.345     bowersj2 5040:                 if ($wgt) {
                   5041:                     $entries{$fields{$dest}}=~s/\s//g;
                   5042:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 5043:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   5044:                                           : 'correct_by_override';
1.596.2.4  raeburn  5045:                     if ($pcr>1) {
                   5046:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   5047:                     }
1.345     bowersj2 5048:                     $grades{"resource.$part.awarded"}=$pcr;
                   5049:                     $grades{"resource.$part.solved"}=$award;
                   5050:                     $points{$part}=1;
                   5051:                 } else {
                   5052:                     $error_msg = "<br />" .
                   5053:                         &mt("Some point values were assigned"
                   5054:                             ." for problems with a weight "
                   5055:                             ."of zero. These values were "
                   5056:                             ."ignored.");
                   5057:                 }
1.244     albertel 5058: 	    } else {
                   5059: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5060: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5061: 		my $store_key=$dest;
                   5062: 		$store_key=~s/^stores/resource/;
                   5063: 		$store_key=~s/_/\./g;
                   5064: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5065: 	    }
1.41      ng       5066: 	}
1.596.2.12.2.  1(raebur 5067:0): 	if (! %grades) {
1.508     www      5068:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5069:         } else {
                   5070: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5071: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5072: 					   $env{'request.course.id'},
                   5073: 					   $domain,$username);
1.508     www      5074: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 5075:0): # Successfully stored
1.508     www      5076: 	      $request->print('.');
1.596.2.4  raeburn  5077: # Remove from grading queue
                   5078:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5079:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5080:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5081:                                              $domain,$username);
1.508     www      5082: 	   } else {
                   5083: 	      $request->print("<p><span class=\"LC_error\">".
                   5084:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5085:                                   "$username:$domain",$result)."</span></p>");
                   5086: 	   }
                   5087: 	   $request->rflush();
                   5088: 	   $countdone++;
                   5089:         }
1.41      ng       5090:     }
1.570     www      5091:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5092:     if (@warnings) {
                   5093:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5094:         $request->print(join(', ',@warnings));
                   5095:     }
1.41      ng       5096:     if (@skipped) {
1.571     www      5097: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5098:         $request->print(join(', ',@skipped));
1.106     albertel 5099:     }
                   5100:     if (@notallowed) {
1.571     www      5101: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5102: 	$request->print(join(', ',@notallowed));
1.41      ng       5103:     }
1.106     albertel 5104:     $request->print("<br />\n");
1.345     bowersj2 5105:     return $error_msg;
1.26      albertel 5106: }
1.44      ng       5107: #------------- end of section for handling csv file upload ---------
                   5108: #
                   5109: #-------------------------------------------------------------------
                   5110: #
1.122     ng       5111: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5112: #
                   5113: #--- Select a page/sequence and a student to grade
1.68      ng       5114: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5115:0):     my ($request,$symb) = @_;
1.68      ng       5116: 
1.539     riegler  5117:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5118:6):     &js_escape(\$alertmsg);
          1(raebur 5119:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5120: 
                   5121: function checkPickOne(formname) {
1.76      ng       5122:     if (radioSelection(formname.student) == null) {
1.539     riegler  5123: 	alert("$alertmsg");
1.68      ng       5124: 	return;
                   5125:     }
1.125     ng       5126:     ptr = pullDownSelection(formname.selectpage);
                   5127:     formname.page.value = formname["page"+ptr].value;
                   5128:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5129:     formname.submit();
                   5130: }
                   5131: 
                   5132: LISTJAVASCRIPT
1.118     ng       5133:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5134:0): 
1.257     albertel 5135:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5136:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5137:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5138:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5139: 
1.398     albertel 5140:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5141: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5142: 
1.80      ng       5143:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5144:     my $map_error;
                   5145:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5146:     if ($map_error) {
                   5147:         $request->print(&navmap_errormsg());
                   5148:         return; 
                   5149:     }
1.137     albertel 5150:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5151: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5152: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5153: 
1.596.2.12.2.  1(raebur 5154:0):     # Collection of hidden fields
                   5155:0):     my $ctr=0;
1.70      ng       5156:     foreach (@$titles) {
                   5157: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5158: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5159: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5160: 	$ctr++;
                   5161:     }
1.72      ng       5162:     $result.='<input type="hidden" name="page" />'."\n".
                   5163: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5164: 
1.432     banghart 5165:     $result.=&build_section_inputs();
1.442     banghart 5166:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5167:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5168:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5169:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5170:0): 
                   5171:0):     # Show grading options
                   5172:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5173:0):     my $select = '<select name="selectpage">'."\n";
                   5174:0):     $ctr=0;
                   5175:0):     foreach (@$titles) {
                   5176:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5177:0):         $select.='<option value="'.$ctr.'"'.
                   5178:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5179:0):             '>'.$showtitle.'</option>'."\n";
                   5180:0):         $ctr++;
                   5181:0):     }
                   5182:0):     $select.= '</select>';
1.72      ng       5183: 
1.596.2.12.2.  1(raebur 5184:0):     $result.=
                   5185:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5186:0):        .$select
                   5187:0):        .&Apache::lonhtmlcommon::row_closure();
                   5188:0): 
                   5189:0):     $result.=
                   5190:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5191:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5192:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5193:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5194:0):            .&mt('yes').'</label>'."\n"
                   5195:0):        .&Apache::lonhtmlcommon::row_closure();
                   5196:0): 
                   5197:0):     $result.=
                   5198:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5199:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5200:0):            .&mt('none').' </label>'."\n"
                   5201:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5202:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5203:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5204:0):            .&mt('all submissions with details').' </label>'
                   5205:0):        .&Apache::lonhtmlcommon::row_closure();
                   5206:0): 
                   5207:0):     $result.=
                   5208:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5209:0):        .'<input type="text" name="CODE" value="" />'
                   5210:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5211:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5212: 
1.596.2.12.2.  1(raebur 5213:0):     # Show list of students to select for grading
                   5214:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5215:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5216: 
1.68      ng       5217:     $request->print($result);
                   5218: 
1.485     albertel 5219:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5220: 	&Apache::loncommon::start_data_table().
                   5221: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5222: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5223: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5224: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5225: 	'<th>'.&nameUserString('header').'</th>'.
                   5226: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5227:  
1.596.2.12.2.  8(raebur 5228:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5229:     my $ptr = 1;
1.294     albertel 5230:     foreach my $student (sort 
                   5231: 			 {
                   5232: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5233: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5234: 			     }
                   5235: 			     return $a cmp $b;
                   5236: 			 } (keys(%$fullname))) {
1.68      ng       5237: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5238: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5239:                                   : '</td>');
1.126     ng       5240: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5241: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5242: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5243: 	$studentTable.=
                   5244: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5245:                          : '');
1.68      ng       5246: 	$ptr++;
                   5247:     }
1.484     albertel 5248:     if ($ptr%2 == 0) {
                   5249: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5250: 	    &Apache::loncommon::end_data_table_row();
                   5251:     }
                   5252:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5253:     $studentTable.='<input type="button" '.
1.589     bisitz   5254:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5255: 
                   5256:     $request->print($studentTable);
                   5257: 
                   5258:     return '';
                   5259: }
                   5260: 
                   5261: sub getSymbMap {
1.582     raeburn  5262:     my ($map_error) = @_;
1.132     bowersj2 5263:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5264:     unless (ref($navmap)) {
                   5265:         if (ref($map_error)) {
                   5266:             $$map_error = 'navmap';
                   5267:         }
                   5268:         return;
                   5269:     }
1.68      ng       5270:     my %symbx = ();
                   5271:     my @titles = ();
1.117     bowersj2 5272:     my $minder = 0;
                   5273: 
                   5274:     # Gather every sequence that has problems.
1.240     albertel 5275:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5276: 					       1,0,1);
1.117     bowersj2 5277:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 5278: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 5279: 	    my $title = $minder.'.'.
                   5280: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5281: 	    push(@titles, $title); # minder in case two titles are identical
                   5282: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5283: 	    $minder++;
1.241     albertel 5284: 	}
1.68      ng       5285:     }
                   5286:     return \@titles,\%symbx;
                   5287: }
                   5288: 
1.72      ng       5289: #
                   5290: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5291: sub displayPage {
1.596.2.12.2.  1(raebur 5292:0):     my ($request,$symb) = @_;
1.257     albertel 5293:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5294:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5295:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5296:     my $pageTitle = $env{'form.page'};
1.103     albertel 5297:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5298:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5299:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5300: 
                   5301:     #need to make sure we have the correct data for later EXT calls, 
                   5302:     #thus invalidate the cache
                   5303:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5304:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5305:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5306:     &Apache::lonnet::clear_EXT_cache_status();
                   5307: 
1.103     albertel 5308:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5309:0): 	$request->print(
                   5310:0):             '<span class="LC_warning">'.
                   5311:0):             &mt('Unable to view requested student. ([_1])',
                   5312:0):                 $env{'form.student'}).
                   5313:0):             '</span>');
          8(raebur 5314:4):         return;
1.103     albertel 5315:     }
1.398     albertel 5316:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5317:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5318: 	'</h3>'."\n";
1.500     albertel 5319:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5320:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5321: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5322:     } else {
                   5323: 	delete($env{'form.CODE'});
                   5324:     }
1.71      ng       5325:     &sub_page_js($request);
                   5326:     $request->print($result);
                   5327: 
1.132     bowersj2 5328:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5329:     unless (ref($navmap)) {
                   5330:         $request->print(&navmap_errormsg());
                   5331:         return;
                   5332:     }
1.257     albertel 5333:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5334:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5335:     if (!$map) {
1.485     albertel 5336: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5337: 	return; 
                   5338:     }
1.68      ng       5339:     my $iterator = $navmap->getIterator($map->map_start(),
                   5340: 					$map->map_finish());
                   5341: 
1.71      ng       5342:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5343: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5344: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5345: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5346: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5347: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5348: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5349:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5350: 
1.382     albertel 5351:     if (defined($env{'form.CODE'})) {
                   5352: 	$studentTable.=
                   5353: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5354:     }
1.381     albertel 5355:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5356: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5357: 
1.594     bisitz   5358:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5359:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5360:         '</span>'."\n".
1.484     albertel 5361: 	&Apache::loncommon::start_data_table().
                   5362: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5363:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5364: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5365: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5366: 
1.329     albertel 5367:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5368:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5369:     $iterator->next(); # skip the first BEGIN_MAP
                   5370:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5371:     while ($depth > 0) {
1.68      ng       5372:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5373:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5374: 
1.385     albertel 5375:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5376: 	    my $parts = $curRes->parts();
1.68      ng       5377:             my $title = $curRes->compTitle();
1.71      ng       5378: 	    my $symbx = $curRes->symb();
1.484     albertel 5379: 	    $studentTable.=
                   5380: 		&Apache::loncommon::start_data_table_row().
                   5381: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5382: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5383:2): 		                        : '<br />('.&mt('[_1]parts',
                   5384:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5385: 		 ).
                   5386: 		 '</td>';
1.71      ng       5387: 	    $studentTable.='<td valign="top">';
1.382     albertel 5388: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5389: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5390: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5391: 					     undef,'both',\%form);
1.71      ng       5392: 	    } else {
1.382     albertel 5393: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5394: 		$companswer =~ s|<form(.*?)>||g;
                   5395: 		$companswer =~ s|</form>||g;
1.71      ng       5396: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5397: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5398: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5399: #		}
1.116     ng       5400: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5401: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5402: 	    }
                   5403: 
1.257     albertel 5404: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5405: 
1.257     albertel 5406: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5407: 		if ($record{'version'} eq '') {
1.485     albertel 5408: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5409: 		} else {
1.116     ng       5410: 		    my %responseType = ();
                   5411: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5412: 			my @responseIds =$curRes->responseIds($partid);
                   5413: 			my @responseType =$curRes->responseType($partid);
                   5414: 			my %responseIds;
                   5415: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5416: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5417: 			}
                   5418: 			$responseType{$partid} = \%responseIds;
1.116     ng       5419: 		    }
1.148     albertel 5420: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5421: 
1.71      ng       5422: 		}
1.257     albertel 5423: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5424: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5425:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5426: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5427: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5428:5): 									'','.submission',undef,
                   5429:5):                                                                         $usec,$identifier);
1.71      ng       5430:  
                   5431: 	    }
1.103     albertel 5432: 	    if (&canmodify($usec)) {
1.585     bisitz   5433:             $studentTable.=&gradeBox_start();
1.103     albertel 5434: 		foreach my $partid (@{$parts}) {
                   5435: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5436: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5437: 		    $question++;
                   5438: 		}
1.585     bisitz   5439:             $studentTable.=&gradeBox_end();
1.196     albertel 5440: 		$prob++;
1.71      ng       5441: 	    }
                   5442: 	    $studentTable.='</td></tr>';
1.68      ng       5443: 
1.103     albertel 5444: 	}
1.68      ng       5445:         $curRes = $iterator->next();
                   5446:     }
1.596.2.12.2.  6(raebur 5447:1):     my $disabled;
                   5448:1):     unless (&canmodify($usec)) {
                   5449:1):         $disabled = ' disabled="disabled"';
                   5450:1):     }
1.68      ng       5451: 
1.589     bisitz   5452:     $studentTable.=
                   5453:         '</table>'."\n".
1.596.2.12.2.  6(raebur 5454:1):         '<input type="button" value="'.&mt('Save').'"'.$disabled.' '.
1.589     bisitz   5455:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5456:         '</form>'."\n";
1.71      ng       5457:     $request->print($studentTable);
                   5458: 
                   5459:     return '';
1.119     ng       5460: }
                   5461: 
                   5462: sub displaySubByDates {
1.148     albertel 5463:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5464:     my $isCODE=0;
1.335     albertel 5465:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5466:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5467:     my $studentTable=&Apache::loncommon::start_data_table().
                   5468: 	&Apache::loncommon::start_data_table_header_row().
                   5469: 	'<th>'.&mt('Date/Time').'</th>'.
                   5470: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5471:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5472: 	'<th>'.&mt('Submission').'</th>'.
                   5473: 	'<th>'.&mt('Status').'</th>'.
                   5474: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5475:     my ($version);
                   5476:     my %mark;
1.148     albertel 5477:     my %orders;
1.119     ng       5478:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5479:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5480: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5481:     }
1.335     albertel 5482: 
                   5483:     my $interaction;
1.525     raeburn  5484:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5485:5):     my (%lastrndseed,%lasttype);
1.119     ng       5486:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5487: 	my $timestamp = 
                   5488: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5489: 	if (exists($$record{$version.':resource.0.version'})) {
                   5490: 	    $interaction = $$record{$version.':resource.0.version'};
                   5491: 	}
1.596.2.12.2.  (raeburn 5492:):         if ($isTask && $env{'form.previousversion'}) {
                   5493:):             next unless ($interaction == $env{'form.previousversion'});
                   5494:):         }
1.335     albertel 5495: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5496: 		             : "$version:resource");
1.467     albertel 5497: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5498: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5499: 	if ($isCODE) {
                   5500: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5501: 	}
1.596.2.12.2.  (raeburn 5502:):         if ($isTask) {
                   5503:):             $studentTable.='<td>'.$interaction.'</td>';
                   5504:):         }
1.119     ng       5505: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5506: 	my @displaySub = ();
                   5507: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5508:             my ($hidden,$type);
                   5509:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5510:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5511:                 $hidden = 1;
                   5512:             }
1.596.2.12.2.  1(raebur 5513:0): 	    my @matchKey;
                   5514:0):             if ($isTask) {
                   5515:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
                   5516:0):             } else {
                   5517:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5518:0):             }
1.122     ng       5519: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5520: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5521: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5522: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5523: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5524:                     
1.335     albertel 5525: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5526: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5527:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5528:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5529:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5530:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5531:                                    .'</span>'
                   5532:                                    .' <b>';
1.596     raeburn  5533:                     if ($hidden) {
                   5534:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5535:                     } else {
1.596.2.2  raeburn  5536:                         my ($trial,$rndseed,$newvariation);
                   5537:                         if ($type eq 'randomizetry') {
                   5538:                             $trial = $$record{"$where.$partid.tries"};
                   5539:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5540:                         }
1.596     raeburn  5541: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5542: 			    $displaySub[0].=&mt('Trial not counted');
                   5543: 		        } else {
                   5544: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5545: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5546:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5547:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5548:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5549:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5550:                                 }
                   5551:                             }
1.596.2.12.2.  4(raebur 5552:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5553:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5554: 		        }
                   5555: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5556:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5557: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5558: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5559: 			    $orders{$partid}->{$responseId}=
                   5560: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5561:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5562: 		        }
1.596.2.2  raeburn  5563: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5564: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5565: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5566:                     }
1.147     albertel 5567: 		}
                   5568: 	    }
1.335     albertel 5569: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5570: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5571: 				    $$record{"$where.$partid.checkedin"},
                   5572: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5573: 					'<br />';
1.335     albertel 5574: 	    }
                   5575: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5576: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5577: 		    lc($$record{"$where.$partid.award"}).' '.
                   5578: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5579: 		    '<br />';
                   5580: 	    }
1.335     albertel 5581: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5582: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5583: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5584: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5585: 		$displaySub[2].=
                   5586: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5587: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5588: 	    }
                   5589: 	}
                   5590: 	# needed because old essay regrader has not parts info
                   5591: 	if (exists $$record{"$version:resource.regrader"}) {
                   5592: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5593: 	}
                   5594: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5595: 	if ($displaySub[2]) {
1.467     albertel 5596: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5597: 	}
1.467     albertel 5598: 	$studentTable.='&nbsp;</td>'.
                   5599: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5600:     }
1.467     albertel 5601:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5602:     return $studentTable;
1.71      ng       5603: }
                   5604: 
                   5605: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5606:0):     my ($request,$symb) = @_;
1.71      ng       5607: 
1.257     albertel 5608:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5609:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5610:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5611:     my $pageTitle = $env{'form.page'};
1.103     albertel 5612:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5613:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5614:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5615:     if (!&canmodify($usec)) {
1.526     raeburn  5616: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5617: 	return;
                   5618:     }
1.398     albertel 5619:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5620:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5621: 	'</h3>'."\n";
1.70      ng       5622: 
1.68      ng       5623:     $request->print($result);
                   5624: 
1.582     raeburn  5625: 
1.132     bowersj2 5626:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5627:     unless (ref($navmap)) {
                   5628:         $request->print(&navmap_errormsg());
                   5629:         return;
                   5630:     }
1.257     albertel 5631:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5632:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5633:     if (!$map) {
1.527     raeburn  5634: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5635: 	return; 
                   5636:     }
1.71      ng       5637:     my $iterator = $navmap->getIterator($map->map_start(),
                   5638: 					$map->map_finish());
1.70      ng       5639: 
1.484     albertel 5640:     my $studentTable=
                   5641: 	&Apache::loncommon::start_data_table().
                   5642: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5643: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5644: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5645: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5646: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5647: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5648: 
                   5649:     $iterator->next(); # skip the first BEGIN_MAP
                   5650:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5651:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5652:     while ($depth > 0) {
1.71      ng       5653:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5654:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5655: 
1.385     albertel 5656:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5657: 	    my $parts = $curRes->parts();
1.71      ng       5658:             my $title = $curRes->compTitle();
                   5659: 	    my $symbx = $curRes->symb();
1.484     albertel 5660: 	    $studentTable.=
                   5661: 		&Apache::loncommon::start_data_table_row().
                   5662: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5663: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5664:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5665: 		.')').'</td>';
1.71      ng       5666: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5667: 
                   5668: 	    my %newrecord=();
                   5669: 	    my @displayPts=();
1.269     raeburn  5670:             my %aggregate = ();
                   5671:             my $aggregateflag = 0;
1.596.2.12.2.  9(raebur 5672:1):             my %queueable;
          1(raebur 5673:5):             if ($env{'form.HIDE'.$prob}) {
                   5674:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5675:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5676:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5677:5):                 $hideflag += $numchgs;
                   5678:5):             }
1.71      ng       5679: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5680: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5681: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.596.2.12.2.  9(raebur 5682:1):                 my @types = $curRes->responseType($partid);
          8(raebur 5683:1):                 if (grep(/^essay$/,@types)) {
                   5684:1):                     $queueable{$partid} = 1;
                   5685:1):                 } else {
          9(raebur 5686:1):                     my @ids = $curRes->responseIds($partid);
          8(raebur 5687:1):                     for (my $i=0; $i < scalar(@ids); $i++) {
          9(raebur 5688:1):                         my $hndgrd = &Apache::lonnet::EXT('resource.'.$partid.'_'.$ids[$i].
          8(raebur 5689:1):                                                           '.handgrade',$symb);
                   5690:1):                         if (lc($hndgrd) eq 'yes') {
                   5691:1):                             $queueable{$partid} = 1;
                   5692:1):                             last;
                   5693:1):                         }
                   5694:1):                     }
                   5695:1):                 }
1.257     albertel 5696: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5697: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5698: 		my $partial = $newpts/$wgt;
                   5699: 		my $score;
                   5700: 		if ($partial > 0) {
                   5701: 		    $score = 'correct_by_override';
1.125     ng       5702: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5703: 		    $score = 'incorrect_by_override';
                   5704: 		}
1.257     albertel 5705: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5706: 		if ($dropMenu eq 'excused') {
1.71      ng       5707: 		    $partial = '';
                   5708: 		    $score = 'excused';
1.125     ng       5709: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5710: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5711: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5712: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5713: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5714: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5715: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5716: 		    $changeflag++;
                   5717: 		    $newpts = '';
1.269     raeburn  5718:                     
                   5719:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5720:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5721:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5722:                     if ($aggtries > 0) {
                   5723:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5724:                         $aggregateflag = 1;
                   5725:                     }
1.71      ng       5726: 		}
1.324     albertel 5727: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5728: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5729: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5730: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5731: 		    '&nbsp;<br />';
1.526     raeburn  5732: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5733: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5734: 		    '&nbsp;<br />';
1.71      ng       5735: 		$question++;
1.380     albertel 5736: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5737: 
1.71      ng       5738: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5739: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5740: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5741: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5742: 
                   5743: 		$changeflag++;
                   5744: 	    }
                   5745: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5746: 		my %record = 
                   5747: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5748: 					     $udom,$uname);
                   5749: 
                   5750: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5751: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5752: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5753: 		    $newrecord{'resource.CODE'} = '';
                   5754: 		}
1.257     albertel 5755: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5756: 					$udom,$uname);
1.382     albertel 5757: 		%record = &Apache::lonnet::restore($symbx,
                   5758: 						   $env{'request.course.id'},
                   5759: 						   $udom,$uname);
1.380     albertel 5760: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
1.596.2.12.2.  8(raebur 5761:1): 					     $cdom,$cnum,$udom,$uname,\%queueable);
1.71      ng       5762: 	    }
1.380     albertel 5763: 	    
1.269     raeburn  5764:             if ($aggregateflag) {
                   5765:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5766:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5767:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5768:             }
1.125     ng       5769: 
1.71      ng       5770: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5771: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5772: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5773: 
1.196     albertel 5774: 	    $prob++;
1.68      ng       5775: 	}
1.71      ng       5776:         $curRes = $iterator->next();
1.68      ng       5777:     }
1.98      albertel 5778: 
1.484     albertel 5779:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5780:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5781: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5782:5): 		  $changeflag).'<br />');
                   5783:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5784:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5785:5):                      $hideflag).'<br />');
                   5786:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5787: 
1.70      ng       5788:     return '';
                   5789: }
                   5790: 
1.72      ng       5791: #-------- end of section for handling grading by page/sequence ---------
                   5792: #
                   5793: #-------------------------------------------------------------------
                   5794: 
1.581     www      5795: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5796: #
                   5797: #------ start of section for handling grading by page/sequence ---------
                   5798: 
1.423     albertel 5799: =pod
                   5800: 
                   5801: =head1 Bubble sheet grading routines
                   5802: 
1.424     albertel 5803:   For this documentation:
                   5804: 
                   5805:    'scanline' refers to the full line of characters
                   5806:    from the file that we are parsing that represents one entire sheet
                   5807: 
                   5808:    'bubble line' refers to the data
1.596.2.6  raeburn  5809:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5810: 
                   5811: 
1.596.2.6  raeburn  5812: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5813: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5814: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5815: one of the predefined configurations for what each scanline looks
                   5816: like.
                   5817: 
                   5818: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5819: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5820: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5821:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5822: invalid student/employee ID
1.424     albertel 5823: 
                   5824: If the CODE option is used that determines the randomization of the
1.556     weissno  5825: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5826: username:domain.
                   5827: 
                   5828: During the validation phase the instructor can choose to skip scanlines. 
                   5829: 
1.596.2.6  raeburn  5830: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5831: 
                   5832:   scantron_original_filename (unmodified original file)
                   5833:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5834:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5835: 
                   5836: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5837: correction information that isn't representable in the bubblesheet
1.424     albertel 5838: file (see &scantron_getfile() for more information)
                   5839: 
                   5840: After all scanlines are either valid, marked as valid or skipped, then
                   5841: foreach line foreach problem in the picked sequence, an ssi request is
                   5842: made that simulates a user submitting their selected letter(s) against
                   5843: the homework problem.
1.423     albertel 5844: 
                   5845: =over 4
                   5846: 
                   5847: 
                   5848: 
                   5849: =item defaultFormData
                   5850: 
                   5851:   Returns html hidden inputs used to hold context/default values.
                   5852: 
                   5853:  Arguments:
                   5854:   $symb - $symb of the current resource 
                   5855: 
                   5856: =cut
1.422     foxr     5857: 
1.81      albertel 5858: sub defaultFormData {
1.324     albertel 5859:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 5860:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5861: }
                   5862: 
1.447     foxr     5863: 
1.423     albertel 5864: =pod 
                   5865: 
                   5866: =item getSequenceDropDown
                   5867: 
                   5868:    Return html dropdown of possible sequences to grade
                   5869:  
                   5870:  Arguments:
1.582     raeburn  5871:    $symb - $symb of the current resource
                   5872:    $map_error - ref to scalar which will container error if
                   5873:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5874: 
                   5875: =cut
1.422     foxr     5876: 
1.75      albertel 5877: sub getSequenceDropDown {
1.582     raeburn  5878:     my ($symb,$map_error)=@_;
1.75      albertel 5879:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5880:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5881:     if (ref($map_error)) {
                   5882:         return if ($$map_error);
                   5883:     }
1.137     albertel 5884:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5885:     my $ctr=0;
                   5886:     foreach (@$titles) {
                   5887: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5888: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5889: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5890: 	    '>'.$showtitle.'</option>'."\n";
                   5891: 	$ctr++;
                   5892:     }
                   5893:     $result.= '</select>';
                   5894:     return $result;
                   5895: }
                   5896: 
1.495     albertel 5897: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5898:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5899: 
                   5900: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5901: 
1.509     raeburn  5902: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5903:                                    # matchresponse or rankresponse, where 
                   5904:                                    # an individual response can have multiple 
                   5905:                                    # lines
1.503     raeburn  5906: 
                   5907: my %responsetype_per_response;     # responsetype for each response
                   5908: 
1.596.2.12.2.  6(raebur 5909:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5910:3):                                    # numbered response. Needed when randomorder
                   5911:3):                                    # or randompick are in use. Key is ID, value 
                   5912:3):                                    # is response number.
                   5913:3): 
1.495     albertel 5914: # Save and restore the bubble lines array to the form env.
                   5915: 
                   5916: 
                   5917: sub save_bubble_lines {
                   5918:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5919: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5920: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5921: 	    $first_bubble_line{$line};
1.503     raeburn  5922:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5923:             $subdivided_bubble_lines{$line};
                   5924:         $env{"form.scantron.responsetype.$line"} =
                   5925:             $responsetype_per_response{$line};
1.495     albertel 5926:     }
1.596.2.12.2.  6(raebur 5927:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5928:3):         my $line = $masterseq_id_responsenum{$resid};
                   5929:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5930:3):     }
1.495     albertel 5931: }
                   5932: 
                   5933: 
                   5934: sub restore_bubble_lines {
                   5935:     my $line = 0;
                   5936:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5937:3):     %masterseq_id_responsenum = ();
1.495     albertel 5938:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5939: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5940: 	$bubble_lines_per_response{$line} = $value;
                   5941: 	$first_bubble_line{$line}  =
                   5942: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5943:         $subdivided_bubble_lines{$line} =
                   5944:             $env{"form.scantron.sub_bubblelines.$line"};
                   5945:         $responsetype_per_response{$line} =
                   5946:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5947:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5948:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5949: 	$line++;
                   5950:     }
                   5951: }
                   5952: 
1.423     albertel 5953: =pod 
                   5954: 
                   5955: =item scantron_filenames
                   5956: 
                   5957:    Returns a list of the scantron files in the current course 
                   5958: 
                   5959: =cut
1.422     foxr     5960: 
1.202     albertel 5961: sub scantron_filenames {
1.257     albertel 5962:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5963:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5964:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5965:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5966:):                                                         $cname,$getpropath);
1.202     albertel 5967:     my @possiblenames;
1.596.2.12.2.  (raeburn 5968:):     if (ref($dirlist) eq 'ARRAY') {
                   5969:):         foreach my $filename (sort(@{$dirlist})) {
                   5970:): 	    ($filename)=split(/&/,$filename);
                   5971:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5972:): 	    $filename=~s/^scantron_orig_//;
                   5973:): 	    push(@possiblenames,$filename);
                   5974:):         }
1.202     albertel 5975:     }
                   5976:     return @possiblenames;
                   5977: }
                   5978: 
1.423     albertel 5979: =pod 
                   5980: 
                   5981: =item scantron_uploads
                   5982: 
                   5983:    Returns  html drop-down list of scantron files in current course.
                   5984: 
                   5985:  Arguments:
                   5986:    $file2grade - filename to set as selected in the dropdown
                   5987: 
                   5988: =cut
1.422     foxr     5989: 
1.202     albertel 5990: sub scantron_uploads {
1.209     ng       5991:     my ($file2grade) = @_;
1.202     albertel 5992:     my $result=	'<select name="scantron_selectfile">';
                   5993:     $result.="<option></option>";
                   5994:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5995: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5996:     }
                   5997:     $result.="</select>";
                   5998:     return $result;
                   5999: }
                   6000: 
1.423     albertel 6001: =pod 
                   6002: 
                   6003: =item scantron_scantab
                   6004: 
                   6005:   Returns html drop down of the scantron formats in the scantronformat.tab
                   6006:   file.
                   6007: 
                   6008: =cut
1.422     foxr     6009: 
1.82      albertel 6010: sub scantron_scantab {
                   6011:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 6012:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 6013:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  6014:     if (@lines > 0) {
                   6015:         foreach my $line (@lines) {
                   6016:             next if (($line =~ /^\#/) || ($line eq ''));
                   6017: 	    my ($name,$descrip)=split(/:/,$line);
                   6018: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   6019:         }
1.82      albertel 6020:     }
                   6021:     $result.='</select>'."\n";
1.518     raeburn  6022:     return $result;
                   6023: }
                   6024: 
1.423     albertel 6025: =pod 
                   6026: 
                   6027: =item scantron_CODElist
                   6028: 
                   6029:   Returns html drop down of the saved CODE lists from current course,
                   6030:   generated from earlier printings.
                   6031: 
                   6032: =cut
1.422     foxr     6033: 
1.186     albertel 6034: sub scantron_CODElist {
1.257     albertel 6035:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6036:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 6037:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   6038:     my $namechoice='<option></option>';
1.225     albertel 6039:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 6040: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 6041: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 6042: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   6043:     }
                   6044:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6045:     return $namechoice;
                   6046: }
                   6047: 
1.423     albertel 6048: =pod 
                   6049: 
                   6050: =item scantron_CODEunique
                   6051: 
                   6052:   Returns the html for "Each CODE to be used once" radio.
                   6053: 
                   6054: =cut
1.422     foxr     6055: 
1.186     albertel 6056: sub scantron_CODEunique {
1.532     bisitz   6057:     my $result='<span class="LC_nobreak">
1.272     albertel 6058:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6059:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6060:                 </span>
1.532     bisitz   6061:                 <span class="LC_nobreak">
1.272     albertel 6062:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6063:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6064:                 </span>';
1.186     albertel 6065:     return $result;
                   6066: }
1.423     albertel 6067: 
                   6068: =pod 
                   6069: 
                   6070: =item scantron_selectphase
                   6071: 
1.596.2.6  raeburn  6072:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6073:   Allows for - starting a grading run.
1.424     albertel 6074:              - downloading existing scan data (original, corrected
1.423     albertel 6075:                                                 or skipped info)
                   6076: 
                   6077:              - uploading new scan data
                   6078: 
                   6079:  Arguments:
                   6080:   $r          - The Apache request object
                   6081:   $file2grade - name of the file that contain the scanned data to score
                   6082: 
                   6083: =cut
1.186     albertel 6084: 
1.75      albertel 6085: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 6086:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6087:     if (!$symb) {return '';}
1.582     raeburn  6088:     my $map_error;
                   6089:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6090:     if ($map_error) {
                   6091:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6092:         return;
                   6093:     }
1.324     albertel 6094:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6095:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6096:     my $format_selector=&scantron_scantab();
1.186     albertel 6097:     my $CODE_selector=&scantron_CODElist();
                   6098:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6099:     my $result;
1.422     foxr     6100: 
1.513     foxr     6101:     $ssi_error = 0;
                   6102: 
1.596.2.4  raeburn  6103:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6104:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6105: 
                   6106:         # Chunk of form to prompt for a scantron file upload.
                   6107: 
                   6108:         $r->print('
1.596.2.12.2.  9(raebur 6109:9):     <br />');
                   6110:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6111:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6112:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6113:9):         &js_escape(\$alertmsg);
                   6114:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6115:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6116:     function checkUpload(formname) {
                   6117:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6118:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6119:             return false;
                   6120:         }
                   6121:         formname.submit();
1.596.2.12.2.  9(raebur 6122:9):     }'."\n".$formatjs));
                   6123:9):         $r->print('
1.596.2.4  raeburn  6124:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6125:                 '.$default_form_data.'
                   6126:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6127:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6128:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6129:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6130:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6131:9):                 <th>
                   6132:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6133:9):                 </th>
                   6134:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6135:9):               '.&Apache::loncommon::start_data_table_row().'
                   6136:9):             <td>
                   6137:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6138:9):         if ($formatoptions) {
                   6139:9):             $r->print('</td>
                   6140:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6141:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6142:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6143:9):                  </td>
                   6144:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6145:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6146:9):                  <td>'
                   6147:9):             );
                   6148:9):         } else {
                   6149:9):             $r->print(' <br />');
                   6150:9):         }
                   6151:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6152:9):               </td>
                   6153:9):              '.&Apache::loncommon::end_data_table_row().'
                   6154:9):              '.&Apache::loncommon::end_data_table().'
                   6155:9):              </form>'
                   6156:9):         );
1.596.2.4  raeburn  6157: 
                   6158:     }
                   6159: 
1.422     foxr     6160:     # Chunk of form to prompt for a file to grade and how:
                   6161: 
1.489     albertel 6162:     $result.= '
                   6163:     <br />
                   6164:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6165:     <input type="hidden" name="command" value="scantron_warning" />
                   6166:     '.$default_form_data.'
                   6167:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6168:        '.&Apache::loncommon::start_data_table_header_row().'
                   6169:             <th colspan="2">
1.492     albertel 6170:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6171:             </th>
                   6172:        '.&Apache::loncommon::end_data_table_header_row().'
                   6173:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6174:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6175:        '.&Apache::loncommon::end_data_table_row().'
                   6176:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6177:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6178:        '.&Apache::loncommon::end_data_table_row().'
                   6179:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6180:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6181:        '.&Apache::loncommon::end_data_table_row().'
                   6182:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6183:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6184:        '.&Apache::loncommon::end_data_table_row().'
                   6185:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6186:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6187:        '.&Apache::loncommon::end_data_table_row().'
                   6188:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6189: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6190:             <td>
1.492     albertel 6191: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6192:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6193:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6194: 	    </td>
1.489     albertel 6195:        '.&Apache::loncommon::end_data_table_row().'
                   6196:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6197:             <td colspan="2">
1.572     www      6198:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6199:             </td>
1.489     albertel 6200:        '.&Apache::loncommon::end_data_table_row().'
                   6201:     '.&Apache::loncommon::end_data_table().'
                   6202:     </form>
                   6203: ';
1.162     albertel 6204:    
                   6205:     $r->print($result);
                   6206: 
1.422     foxr     6207:     # Chunk of the form that prompts to view a scoring office file,
                   6208:     # corrected file, skipped records in a file.
                   6209: 
1.489     albertel 6210:     $r->print('
                   6211:    <br />
                   6212:    <form action="/adm/grades" name="scantron_download">
                   6213:      '.$default_form_data.'
                   6214:      <input type="hidden" name="command" value="scantron_download" />
                   6215:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6216:        '.&Apache::loncommon::start_data_table_header_row().'
                   6217:               <th>
1.492     albertel 6218:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6219:               </th>
                   6220:        '.&Apache::loncommon::end_data_table_header_row().'
                   6221:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6222:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6223:                 <br />
1.492     albertel 6224:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6225:        '.&Apache::loncommon::end_data_table_row().'
                   6226:      '.&Apache::loncommon::end_data_table().'
                   6227:    </form>
                   6228:    <br />
                   6229: ');
1.162     albertel 6230: 
1.457     banghart 6231:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6232: 
1.596.2.12.2.  8(raebur 6233:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6234:              $default_form_data."\n".
                   6235:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6236:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6237:              '<th colspan="2">
1.572     www      6238:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6239:              '</th>'."\n".
                   6240:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6241:               &Apache::loncommon::start_data_table_row()."\n".
                   6242:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6243:               '<td> '.$sequence_selector.' </td>'.
                   6244:               &Apache::loncommon::end_data_table_row()."\n".
                   6245:               &Apache::loncommon::start_data_table_row()."\n".
                   6246:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6247:               '<td> '.$file_selector.' </td>'."\n".
                   6248:               &Apache::loncommon::end_data_table_row()."\n".
                   6249:               &Apache::loncommon::start_data_table_row()."\n".
                   6250:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6251:               '<td> '.$format_selector.' </td>'."\n".
                   6252:               &Apache::loncommon::end_data_table_row()."\n".
                   6253:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6254:               '<td> '.&mt('Options').' </td>'."\n".
                   6255:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6256:               &Apache::loncommon::end_data_table_row()."\n".
                   6257:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6258:               '<td colspan="2">'."\n".
                   6259:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6260:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6261:               '</td>'."\n".
                   6262:               &Apache::loncommon::end_data_table_row()."\n".
                   6263:               &Apache::loncommon::end_data_table()."\n".
                   6264:               '</form><br />');
                   6265:     return;
1.75      albertel 6266: }
                   6267: 
1.423     albertel 6268: =pod 
                   6269: 
                   6270: =item username_to_idmap
                   6271: 
1.556     weissno  6272:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6273:     student username:domain.
                   6274: 
                   6275:   Arguments:
                   6276: 
                   6277:     $classlist - reference to the class list hash. This is a hash
                   6278:                  keyed by student name:domain  whose elements are references
1.424     albertel 6279:                  to arrays containing various chunks of information
1.423     albertel 6280:                  about the student. (See loncoursedata for more info).
                   6281: 
                   6282:   Returns
                   6283:     %idmap - the constructed hash
                   6284: 
                   6285: =cut
                   6286: 
1.82      albertel 6287: sub username_to_idmap {
                   6288:     my ($classlist)= @_;
                   6289:     my %idmap;
                   6290:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6291:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6292:5):         unless ($id eq '') {
                   6293:5):             if (!exists($idmap{$id})) {
                   6294:5):                 $idmap{$id} = $student;
                   6295:5):             } else {
                   6296:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6297:5):                 if ($status eq 'Active') {
                   6298:5):                     $idmap{$id} = $student;
                   6299:5):                 }
                   6300:5):             }
                   6301:5):         }
1.82      albertel 6302:     }
                   6303:     return %idmap;
                   6304: }
1.423     albertel 6305: 
                   6306: =pod
                   6307: 
1.424     albertel 6308: =item scantron_fixup_scanline
1.423     albertel 6309: 
                   6310:    Process a requested correction to a scanline.
                   6311: 
                   6312:   Arguments:
1.596.2.12.2.  9(raebur 6313:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6314:     $scan_data         - hash of correction information 
                   6315:                           (see &scantron_getfile())
                   6316:     $line              - existing scanline
                   6317:     $whichline         - line number of the passed in scanline
                   6318:     $field             - type of change to process 
                   6319:                          (either 
1.573     bisitz   6320:                           'ID'     -> correct the student/employee ID
1.423     albertel 6321:                           'CODE'   -> correct the CODE
                   6322:                           'answer' -> fixup the submitted answers)
                   6323:     
                   6324:    $args               - hash of additional info,
                   6325:                           - 'ID' 
                   6326:                                'newid' -> studentID to use in replacement
1.424     albertel 6327:                                           of existing one
1.423     albertel 6328:                           - 'CODE' 
                   6329:                                'CODE_ignore_dup' - set to true if duplicates
                   6330:                                                    should be ignored.
                   6331: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6332:                                         if the existing unfound code should
1.423     albertel 6333:                                         be used as is
                   6334:                           - 'answer'
                   6335:                                'response' - new answer or 'none' if blank
                   6336:                                'question' - the bubble line to change
1.503     raeburn  6337:                                'questionnum' - the question identifier,
                   6338:                                                may include subquestion. 
1.423     albertel 6339: 
                   6340:   Returns:
                   6341:     $line - the modified scanline
                   6342: 
                   6343:   Side effects: 
                   6344:     $scan_data - may be updated
                   6345: 
                   6346: =cut
                   6347: 
1.82      albertel 6348: 
1.157     albertel 6349: sub scantron_fixup_scanline {
                   6350:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6351:     if ($field eq 'ID') {
                   6352: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6353: 	    return ($line,1,'New value too large');
1.157     albertel 6354: 	}
                   6355: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6356: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6357: 				     $args->{'newid'});
                   6358: 	}
                   6359: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6360: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6361: 	if ($args->{'newid'}=~/^\s*$/) {
                   6362: 	    &scan_data($scan_data,"$whichline.user",
                   6363: 		       $args->{'username'}.':'.$args->{'domain'});
                   6364: 	}
1.186     albertel 6365:     } elsif ($field eq 'CODE') {
1.192     albertel 6366: 	if ($args->{'CODE_ignore_dup'}) {
                   6367: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6368: 	}
                   6369: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6370: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6371: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6372: 		return ($line,1,'New CODE value too large');
                   6373: 	    }
                   6374: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6375: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6376: 	    }
                   6377: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6378: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6379: 	}
1.157     albertel 6380:     } elsif ($field eq 'answer') {
1.497     foxr     6381: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6382: 	my $off=$scantron_config->{'Qoff'};
                   6383: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6384: 	my $answer=${off}x$length;
                   6385: 	if ($args->{'response'} eq 'none') {
                   6386: 	    &scan_data($scan_data,
1.503     raeburn  6387: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6388: 	} else {
                   6389: 	    if ($on eq 'letter') {
                   6390: 		my @alphabet=('A'..'Z');
                   6391: 		$answer=$alphabet[$args->{'response'}];
                   6392: 	    } elsif ($on eq 'number') {
                   6393: 		$answer=$args->{'response'}+1;
                   6394: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6395: 	    } else {
1.497     foxr     6396: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6397: 	    }
1.497     foxr     6398: 	    &scan_data($scan_data,
1.503     raeburn  6399: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6400: 	}
1.497     foxr     6401: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6402: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6403:     }
                   6404:     return $line;
                   6405: }
1.423     albertel 6406: 
                   6407: =pod
                   6408: 
                   6409: =item scan_data
                   6410: 
                   6411:     Edit or look up  an item in the scan_data hash.
                   6412: 
                   6413:   Arguments:
                   6414:     $scan_data  - The hash (see scantron_getfile)
                   6415:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6416:                   scantronfilename_key).
1.423     albertel 6417:     $data        - New value of the hash entry.
                   6418:     $delete      - If true, the entry is removed from the hash.
                   6419: 
                   6420:   Returns:
                   6421:     The new value of the hash table field (undefined if deleted).
                   6422: 
                   6423: =cut
                   6424: 
                   6425: 
1.157     albertel 6426: sub scan_data {
                   6427:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6428:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6429:     if (defined($value)) {
                   6430: 	$scan_data->{$filename.'_'.$key} = $value;
                   6431:     }
                   6432:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6433:     return $scan_data->{$filename.'_'.$key};
                   6434: }
1.423     albertel 6435: 
1.495     albertel 6436: # ----- These first few routines are general use routines.----
                   6437: 
                   6438: # Return the number of occurences of a pattern in a string.
                   6439: 
                   6440: sub occurence_count {
                   6441:     my ($string, $pattern) = @_;
                   6442: 
                   6443:     my @matches = ($string =~ /$pattern/g);
                   6444: 
                   6445:     return scalar(@matches);
                   6446: }
                   6447: 
                   6448: 
                   6449: # Take a string known to have digits and convert all the
                   6450: # digits into letters in the range J,A..I.
                   6451: 
                   6452: sub digits_to_letters {
                   6453:     my ($input) = @_;
                   6454: 
                   6455:     my @alphabet = ('J', 'A'..'I');
                   6456: 
                   6457:     my @input    = split(//, $input);
                   6458:     my $output ='';
                   6459:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6460: 	if ($input[$i] =~ /\d/) {
                   6461: 	    $output .= $alphabet[$input[$i]];
                   6462: 	} else {
                   6463: 	    $output .= $input[$i];
                   6464: 	}
                   6465:     }
                   6466:     return $output;
                   6467: }
                   6468: 
1.423     albertel 6469: =pod 
                   6470: 
                   6471: =item scantron_parse_scanline
                   6472: 
                   6473:   Decodes a scanline from the selected scantron file
                   6474: 
                   6475:  Arguments:
                   6476:     line             - The text of the scantron file line to process
                   6477:     whichline        - Line number
                   6478:     scantron_config  - Hash describing the format of the scantron lines.
                   6479:     scan_data        - Hash of extra information about the scanline
                   6480:                        (see scantron_getfile for more information)
                   6481:     just_header      - True if should not process question answers but only
                   6482:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6483:3):     randomorder      - True if randomorder in use
                   6484:3):     randompick       - True if randompick in use
                   6485:3):     sequence         - Exam folder URL
                   6486:3):     master_seq       - Ref to array containing symbs in exam folder
                   6487:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6488:3):                        (corresponding values are resource objects)
                   6489:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6490:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6491:3):                        are refs to an array of resource objects, ordered
                   6492:3):                        according to order used for CODE, when randomorder
                   6493:3):                        and or randompick are in use.
                   6494:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6495:3):                        for current line to question number used for same question
                   6496:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6497:3):     startline        - Ref to hash where key is question number (0 is first)
                   6498:3):                        and value is number of first bubble line for current 
                   6499:3):                        student or code-based randompick and/or randomorder.
                   6500:3):     totalref         - Ref of scalar used to score total number of bubble
                   6501:3):                        lines needed for responses in a scan line (used when
                   6502:3):                        randompick in use. 
                   6503:3): 
1.423     albertel 6504:  Returns:
                   6505:    Hash containing the result of parsing the scanline
                   6506: 
                   6507:    Keys are all proceeded by the string 'scantron.'
                   6508: 
                   6509:        CODE    - the CODE in use for this scanline
                   6510:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6511:                  by the operator
                   6512:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6513:                             CODEs were selected, but the usage has been
                   6514:                             forced by the operator
1.556     weissno  6515:        ID  - student/employee ID
1.423     albertel 6516:        PaperID - if used, the ID number printed on the sheet when the 
                   6517:                  paper was scanned
                   6518:        FirstName - first name from the sheet
                   6519:        LastName  - last name from the sheet
                   6520: 
                   6521:      if just_header was not true these key may also exist
                   6522: 
1.447     foxr     6523:        missingerror - a list of bubble ranges that are considered to be answers
                   6524:                       to a single question that don't have any bubbles filled in.
                   6525:                       Of the form questionnumber:firstbubblenumber:count.
                   6526:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6527:                       to a single question that have more than one bubble filled in.
                   6528:                       Of the form questionnumber::firstbubblenumber:count
                   6529:    
                   6530:                 In the above, count is the number of bubble responses in the
                   6531:                 input line needed to represent the possible answers to the question.
                   6532:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6533:                 per line would have count = 2.
                   6534: 
1.423     albertel 6535:        maxquest     - the number of the last bubble line that was parsed
                   6536: 
                   6537:        (<number> starts at 1)
                   6538:        <number>.answer - zero or more letters representing the selected
                   6539:                          letters from the scanline for the bubble line 
                   6540:                          <number>.
                   6541:                          if blank there was either no bubble or there where
                   6542:                          multiple bubbles, (consult the keys missingerror and
                   6543:                          doubleerror if this is an error condition)
                   6544: 
                   6545: =cut
                   6546: 
1.82      albertel 6547: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6548:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6549:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6550:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6551: 
1.82      albertel 6552:     my %record;
1.596.2.12.2.  6(raebur 6553:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6554:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6555: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6556: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6557: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6558: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6559: 	    $record{'scantron.CODE'}=substr($data,
                   6560: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6561: 					    $$scantron_config{'CODElength'});
1.191     albertel 6562: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6563: 		$record{'scantron.useCODE'}=1;
                   6564: 	    }
1.192     albertel 6565: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6566: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6567: 	    }
1.82      albertel 6568: 	} else {
                   6569: 	    #FIXME interpret first N questions
                   6570: 	}
                   6571:     }
1.83      albertel 6572:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6573: 				  $$scantron_config{'IDlength'});
1.157     albertel 6574:     $record{'scantron.PaperID'}=
                   6575: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6576: 	       $$scantron_config{'PaperIDlength'});
                   6577:     $record{'scantron.FirstName'}=
                   6578: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6579: 	       $$scantron_config{'FirstNamelength'});
                   6580:     $record{'scantron.LastName'}=
                   6581: 	substr($data,$$scantron_config{'LastName'}-1,
                   6582: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6583:     if ($just_header) { return \%record; }
1.194     albertel 6584: 
1.82      albertel 6585:     my @alphabet=('A'..'Z');
                   6586:     my $questnum=0;
1.447     foxr     6587:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6588: 
1.596.2.12.2.  6(raebur 6589:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6590:3):     if ($randompick || $randomorder) {
                   6591:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6592:3):                                          $master_seq,$symb_to_resource,
                   6593:3):                                          $partids_by_symb,$orderedforcode,
                   6594:3):                                          $respnumlookup,$startline);
                   6595:3):         if ($total) {
                   6596:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6597:3):         }
                   6598:3):         if (ref($totalref)) {
                   6599:3):             $$totalref = $total;
                   6600:3):         }
                   6601:3):     }
                   6602:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6603:     chomp($questions);		# Get rid of any trailing \n.
                   6604:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6605:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6606:3):         my $answers_needed;
                   6607:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6608:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6609:3):         } else {
                   6610:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6611:3):         }
1.503     raeburn  6612:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6613:                              || 1;
                   6614:         $questnum++;
                   6615:         my $quest_id = $questnum;
                   6616:         my $currentquest = substr($questions,0,$answer_length);
                   6617:         $questions       = substr($questions,$answer_length);
                   6618:         if (length($currentquest) < $answer_length) { next; }
                   6619: 
1.596.2.12.2.  6(raebur 6620:3):         my $subdivided;
                   6621:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6622:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6623:3):         } else {
                   6624:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6625:3):         }
                   6626:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6627:             my $subquestnum = 1;
                   6628:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6629:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6630:             foreach my $subans (@subanswers_needed) {
                   6631:                 my $subans_length =
                   6632:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6633:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6634:                 $subquestions   = substr($subquestions,$subans_length);
                   6635:                 $quest_id = "$questnum.$subquestnum";
                   6636:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6637:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6638:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6639:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6640:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6641:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6642:                 } else {
                   6643:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6644:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6645:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6646:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6647:                 }
                   6648:                 $subquestnum ++;
                   6649:             }
                   6650:         } else {
                   6651:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6652:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6653:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6654:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6655:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6656:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6657:             } else {
                   6658:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6659:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6660:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6661:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6662:             }
                   6663:         }
                   6664:     }
                   6665:     $record{'scantron.maxquest'}=$questnum;
                   6666:     return \%record;
                   6667: }
1.447     foxr     6668: 
1.596.2.12.2.  6(raebur 6669:3): sub get_master_seq {
          0(raebur 6670:2):     my ($resources,$master_seq,$symb_to_resource,$need_symb_in_map,$symb_for_examcode) = @_;
          6(raebur 6671:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6672:3):                    (ref($symb_to_resource) eq 'HASH'));
          0(raebur 6673:2):     if ($need_symb_in_map) {
                   6674:2):         return unless (ref($symb_for_examcode) eq 'HASH');
                   6675:2):     }
          6(raebur 6676:3):     my $resource_error;
                   6677:3):     foreach my $resource (@{$resources}) {
                   6678:3):         my $ressymb;
                   6679:3):         if (ref($resource)) {
                   6680:3):             $ressymb = $resource->symb();
                   6681:3):             push(@{$master_seq},$ressymb);
                   6682:3):             $symb_to_resource->{$ressymb} = $resource;
          0(raebur 6683:2):             if ($need_symb_in_map) {
                   6684:2):                 unless ($resource->is_map()) {
                   6685:2):                     my $map=(&Apache::lonnet::decode_symb($ressymb))[0];
                   6686:2):                     unless (exists($symb_for_examcode->{$map})) {
                   6687:2):                         $symb_for_examcode->{$map} = $ressymb;
                   6688:2):                     }
                   6689:2):                 }
                   6690:2):             }
          6(raebur 6691:3):         } else {
                   6692:3):             $resource_error = 1;
                   6693:3):             last;
                   6694:3):         }
                   6695:3):     }
                   6696:3):     return $resource_error;
                   6697:3): }
                   6698:3): 
                   6699:3): sub get_respnum_lookups {
                   6700:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6701:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6702:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6703:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6704:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6705:3):                    (ref($startline) eq 'HASH'));
                   6706:3):     my ($user,$scancode);
                   6707:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6708:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6709:3):         $scancode = $record->{'scantron.CODE'};
                   6710:3):     } else {
                   6711:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6712:3):     }
                   6713:3):     my @mapresources =
                   6714:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6715:3):                      $orderedforcode);
                   6716:3):     my $total = 0;
                   6717:3):     my $count = 0;
                   6718:3):     foreach my $resource (@mapresources) {
                   6719:3):         my $id = $resource->id();
                   6720:3):         my $symb = $resource->symb();
                   6721:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6722:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6723:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6724:3):                 if ($respnum ne '') {
                   6725:3):                     $respnumlookup->{$count} = $respnum;
                   6726:3):                     $startline->{$count} = $total;
                   6727:3):                     $total += $bubble_lines_per_response{$respnum};
                   6728:3):                     $count ++;
                   6729:3):                 }
                   6730:3):             }
                   6731:3):         }
                   6732:3):     }
                   6733:3):     return $total;
                   6734:3): }
                   6735:3): 
1.503     raeburn  6736: sub scantron_validator_lettnum {
                   6737:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6738:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6739:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6740: 
                   6741:     # Qon 'letter' implies for each slot in currquest we have:
                   6742:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6743:     #    about anything else (esp. a value of Qoff) for missing
                   6744:     #    bubbles.
                   6745:     #
                   6746:     # Qon 'number' implies each slot gives a digit that indexes the
                   6747:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6748:     #    and * or ? for double bubbles on a single line.
                   6749:     #
1.447     foxr     6750: 
1.503     raeburn  6751:     my $matchon;
                   6752:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6753:         $matchon = '[A-Z]';
                   6754:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6755:         $matchon = '\d';
                   6756:     }
                   6757:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6758:3):     my $responsenum = $questnum-1;
                   6759:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6760:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6761:3):     }
                   6762:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6763:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6764:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6765:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6766:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6767:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6768:         my @singlelines = split('',$currquest);
                   6769:         foreach my $entry (@singlelines) {
                   6770:             $occurrences = &occurence_count($entry,$matchon);
                   6771:             if ($occurrences > 1) {
                   6772:                 last;
                   6773:             }
1.596.2.12.2.  6(raebur 6774:3):         }
1.503     raeburn  6775:     } else {
                   6776:         $occurrences = &occurence_count($currquest,$matchon); 
                   6777:     }
                   6778:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6779:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6780:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6781:             my $bubble = substr($currquest,$ans,1);
                   6782:             if ($bubble =~ /$matchon/ ) {
                   6783:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6784:                     if ($bubble == 0) {
                   6785:                         $bubble = 10; 
                   6786:                     }
                   6787:                     $record->{"scantron.$ansnum.answer"} = 
                   6788:                         $alphabet->[$bubble-1];
                   6789:                 } else {
                   6790:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6791:                 }
                   6792:             } else {
                   6793:                 $record->{"scantron.$ansnum.answer"}='';
                   6794:             }
                   6795:             $ansnum++;
                   6796:         }
                   6797:     } elsif (!defined($currquest)
                   6798:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6799:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6800:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6801:             $record->{"scantron.$ansnum.answer"}='';
                   6802:             $ansnum++;
                   6803:         }
                   6804:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6805:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6806:         }
                   6807:     } else {
                   6808:         if ($$scantron_config{'Qon'} eq 'number') {
                   6809:             $currquest = &digits_to_letters($currquest);            
                   6810:         }
                   6811:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6812:             my $bubble = substr($currquest,$ans,1);
                   6813:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6814:             $ansnum++;
                   6815:         }
                   6816:     }
                   6817:     return $ansnum;
                   6818: }
1.447     foxr     6819: 
1.503     raeburn  6820: sub scantron_validator_positional {
                   6821:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6822:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6823:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6824: 
1.503     raeburn  6825:     # Otherwise there's a positional notation;
                   6826:     # each bubble line requires Qlength items, and there are filled in
                   6827:     # bubbles for each case where there 'Qon' characters.
                   6828:     #
1.447     foxr     6829: 
1.503     raeburn  6830:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6831: 
1.503     raeburn  6832:     # If the split only gives us one element.. the full length of the
                   6833:     # answer string, no bubbles are filled in:
1.447     foxr     6834: 
1.507     raeburn  6835:     if ($answers_needed eq '') {
                   6836:         return;
                   6837:     }
                   6838: 
1.503     raeburn  6839:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6840:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6841:             $record->{"scantron.$ansnum.answer"}='';
                   6842:             $ansnum++;
                   6843:         }
                   6844:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6845:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6846:         }
                   6847:     } elsif (scalar(@array) == 2) {
                   6848:         my $location = length($array[0]);
                   6849:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6850:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6851:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6852:             if ($ans eq $line_num) {
                   6853:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6854:             } else {
                   6855:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6856:             }
                   6857:             $ansnum++;
                   6858:          }
                   6859:     } else {
                   6860:         #  If there's more than one instance of a bubble character
                   6861:         #  That's a double bubble; with positional notation we can
                   6862:         #  record all the bubbles filled in as well as the
                   6863:         #  fact this response consists of multiple bubbles.
                   6864:         #
1.596.2.12.2.  6(raebur 6865:3):         my $responsenum = $questnum-1;
                   6866:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6867:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6868:3):         }
                   6869:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6870:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6871:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6872:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6873:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6874:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6875:             my $doubleerror = 0;
                   6876:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6877:                    (!$doubleerror)) {
                   6878:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6879:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6880:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6881:                if (length(@currarray) > 2) {
                   6882:                    $doubleerror = 1;
                   6883:                } 
                   6884:             }
                   6885:             if ($doubleerror) {
                   6886:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6887:             }
                   6888:         } else {
                   6889:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6890:         }
                   6891:         my $item = $ansnum;
                   6892:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6893:             $record->{"scantron.$item.answer"} = '';
                   6894:             $item ++;
                   6895:         }
1.447     foxr     6896: 
1.503     raeburn  6897:         my @ans=@array;
                   6898:         my $i=0;
                   6899:         my $increment = 0;
                   6900:         while ($#ans) {
                   6901:             $i+=length($ans[0]) + $increment;
                   6902:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6903:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6904:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6905:             shift(@ans);
                   6906:             $increment = 1;
                   6907:         }
                   6908:         $ansnum += $answers_needed;
1.82      albertel 6909:     }
1.503     raeburn  6910:     return $ansnum;
1.82      albertel 6911: }
                   6912: 
1.423     albertel 6913: =pod
                   6914: 
                   6915: =item scantron_add_delay
                   6916: 
                   6917:    Adds an error message that occurred during the grading phase to a
                   6918:    queue of messages to be shown after grading pass is complete
                   6919: 
                   6920:  Arguments:
1.424     albertel 6921:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6922:    $scanline    - the scanline that caused the error
                   6923:    $errormesage - the error message
                   6924:    $errorcode   - a numeric code for the error
                   6925: 
                   6926:  Side Effects:
1.424     albertel 6927:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6928: 
                   6929: =cut
                   6930: 
1.82      albertel 6931: sub scantron_add_delay {
1.140     albertel 6932:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6933:     push(@$delayqueue,
                   6934: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6935: 	  'ecode' => $errorcode }
                   6936: 	 );
1.82      albertel 6937: }
                   6938: 
1.423     albertel 6939: =pod
                   6940: 
                   6941: =item scantron_find_student
                   6942: 
1.424     albertel 6943:    Finds the username for the current scanline
                   6944: 
                   6945:   Arguments:
                   6946:    $scantron_record - hash result from scantron_parse_scanline
                   6947:    $scan_data       - hash of correction information 
                   6948:                       (see &scantron_getfile() form more information)
                   6949:    $idmap           - hash from &username_to_idmap()
                   6950:    $line            - number of current scanline
                   6951:  
                   6952:   Returns:
                   6953:    Either 'username:domain' or undef if unknown
                   6954: 
1.423     albertel 6955: =cut
                   6956: 
1.82      albertel 6957: sub scantron_find_student {
1.157     albertel 6958:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6959:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6960:     if ($scanID =~ /^\s*$/) {
                   6961:  	return &scan_data($scan_data,"$line.user");
                   6962:     }
1.83      albertel 6963:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6964:  	if (lc($id) eq lc($scanID)) {
                   6965:  	    return $$idmap{$id};
                   6966:  	}
1.83      albertel 6967:     }
                   6968:     return undef;
                   6969: }
                   6970: 
1.423     albertel 6971: =pod
                   6972: 
                   6973: =item scantron_filter
                   6974: 
1.424     albertel 6975:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6976:    hidden resources was selected
                   6977: 
1.423     albertel 6978: =cut
                   6979: 
1.83      albertel 6980: sub scantron_filter {
                   6981:     my ($curres)=@_;
1.331     albertel 6982: 
                   6983:     if (ref($curres) && $curres->is_problem()) {
                   6984: 	# if the user has asked to not have either hidden
                   6985: 	# or 'randomout' controlled resources to be graded
                   6986: 	# don't include them
                   6987: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6988: 	    && $curres->randomout) {
                   6989: 	    return 0;
                   6990: 	}
1.83      albertel 6991: 	return 1;
                   6992:     }
                   6993:     return 0;
1.82      albertel 6994: }
                   6995: 
1.423     albertel 6996: =pod
                   6997: 
                   6998: =item scantron_process_corrections
                   6999: 
1.424     albertel 7000:    Gets correction information out of submitted form data and corrects
                   7001:    the scanline
                   7002: 
1.423     albertel 7003: =cut
                   7004: 
1.157     albertel 7005: sub scantron_process_corrections {
                   7006:     my ($r) = @_;
1.596.2.12.2.  9(raebur 7007:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7008:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7009:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 7010:     my $which=$env{'form.scantron_line'};
1.200     albertel 7011:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 7012:     my ($skip,$err,$errmsg);
1.257     albertel 7013:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 7014: 	$skip=1;
1.257     albertel 7015:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   7016: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   7017: 	    $env{'form.scantron_domain'};
1.157     albertel 7018: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   7019: 	($line,$err,$errmsg)=
                   7020: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   7021: 				     'ID',{'newid'=>$newid,
1.257     albertel 7022: 				    'username'=>$env{'form.scantron_username'},
                   7023: 				    'domain'=>$env{'form.scantron_domain'}});
                   7024:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   7025: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 7026: 	my $newCODE;
1.192     albertel 7027: 	my %args;
1.190     albertel 7028: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 7029: 	    $newCODE='use_unfound';
1.190     albertel 7030: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 7031: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 7032: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 7033: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 7034: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 7035: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 7036: 	}
1.257     albertel 7037: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 7038: 	    $args{'CODE_ignore_dup'}=1;
                   7039: 	}
                   7040: 	$args{'CODE'}=$newCODE;
1.186     albertel 7041: 	($line,$err,$errmsg)=
                   7042: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 7043: 				     'CODE',\%args);
1.257     albertel 7044:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   7045: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 7046: 	    ($line,$err,$errmsg)=
                   7047: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   7048: 					 $which,'answer',
                   7049: 					 { 'question'=>$question,
1.503     raeburn  7050: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   7051:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 7052: 	    if ($err) { last; }
                   7053: 	}
                   7054:     }
                   7055:     if ($err) {
1.596.2.12.2.  0(raebur 7056:3): 	$r->print(
                   7057:3):             '<p class="LC_error">'
                   7058:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7059:3):                 $errmsg)
          1(raebur 7060:3):            .'</p>');
1.157     albertel 7061:     } else {
1.200     albertel 7062: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7063: 	&scantron_putfile($scanlines,$scan_data);
                   7064:     }
                   7065: }
                   7066: 
1.423     albertel 7067: =pod
                   7068: 
                   7069: =item reset_skipping_status
                   7070: 
1.424     albertel 7071:    Forgets the current set of remember skipped scanlines (and thus
                   7072:    reverts back to considering all lines in the
                   7073:    scantron_skipped_<filename> file)
                   7074: 
1.423     albertel 7075: =cut
                   7076: 
1.200     albertel 7077: sub reset_skipping_status {
                   7078:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7079:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7080:     &scantron_putfile(undef,$scan_data);
                   7081: }
                   7082: 
1.423     albertel 7083: =pod
                   7084: 
                   7085: =item start_skipping
                   7086: 
1.424     albertel 7087:    Marks a scanline to be skipped. 
                   7088: 
1.423     albertel 7089: =cut
                   7090: 
1.376     albertel 7091: sub start_skipping {
1.200     albertel 7092:     my ($scan_data,$i)=@_;
                   7093:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7094:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7095: 	$remembered{$i}=2;
                   7096:     } else {
                   7097: 	$remembered{$i}=1;
                   7098:     }
1.200     albertel 7099:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7100: }
                   7101: 
1.423     albertel 7102: =pod
                   7103: 
                   7104: =item should_be_skipped
                   7105: 
1.424     albertel 7106:    Checks whether a scanline should be skipped.
                   7107: 
1.423     albertel 7108: =cut
                   7109: 
1.200     albertel 7110: sub should_be_skipped {
1.376     albertel 7111:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7112:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7113: 	# not redoing old skips
1.376     albertel 7114: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7115: 	return 0;
                   7116:     }
                   7117:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7118: 
                   7119:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7120: 	return 0;
                   7121:     }
1.200     albertel 7122:     return 1;
                   7123: }
                   7124: 
1.423     albertel 7125: =pod
                   7126: 
                   7127: =item remember_current_skipped
                   7128: 
1.424     albertel 7129:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7130:    file and remembers them into scan_data for later use.
                   7131: 
1.423     albertel 7132: =cut
                   7133: 
1.200     albertel 7134: sub remember_current_skipped {
                   7135:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7136:     my %to_remember;
                   7137:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7138: 	if ($scanlines->{'skipped'}[$i]) {
                   7139: 	    $to_remember{$i}=1;
                   7140: 	}
                   7141:     }
1.376     albertel 7142: 
1.200     albertel 7143:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7144:     &scantron_putfile(undef,$scan_data);
                   7145: }
                   7146: 
1.423     albertel 7147: =pod
                   7148: 
                   7149: =item check_for_error
                   7150: 
1.424     albertel 7151:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7152:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7153:     something went wrong.
                   7154: 
1.423     albertel 7155: =cut
                   7156: 
1.200     albertel 7157: sub check_for_error {
                   7158:     my ($r,$result)=@_;
                   7159:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7160: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7161:     }
                   7162: }
1.157     albertel 7163: 
1.423     albertel 7164: =pod
                   7165: 
                   7166: =item scantron_warning_screen
                   7167: 
1.424     albertel 7168:    Interstitial screen to make sure the operator has selected the
                   7169:    correct options before we start the validation phase.
                   7170: 
1.423     albertel 7171: =cut
                   7172: 
1.203     albertel 7173: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7174:0):     my ($button_text,$symb)=@_;
1.257     albertel 7175:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7176:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7177:     my $CODElist;
1.284     albertel 7178:     if ($scantron_config{'CODElocation'} &&
                   7179: 	$scantron_config{'CODEstart'} &&
                   7180: 	$scantron_config{'CODElength'}) {
                   7181: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7182:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7183: 	$CODElist=
1.492     albertel 7184: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7185: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7186:     }
1.596.2.12.2.  (raeburn 7187:):     my $lastbubblepoints;
                   7188:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7189:):         $lastbubblepoints =
                   7190:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7191:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7192:):     }
1.492     albertel 7193:     return ('
1.203     albertel 7194: <p>
1.492     albertel 7195: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7196:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7197: </p>
                   7198: <table>
1.492     albertel 7199: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7200: <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 7201:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7202: </table>
1.596.2.12.2.  1(raebur 7203:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7204: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 7205: 
                   7206: <br />
1.492     albertel 7207: ');
1.203     albertel 7208: }
                   7209: 
1.423     albertel 7210: =pod
                   7211: 
                   7212: =item scantron_do_warning
                   7213: 
1.424     albertel 7214:    Check if the operator has picked something for all required
                   7215:    fields. Error out if something is missing.
                   7216: 
1.423     albertel 7217: =cut
                   7218: 
1.203     albertel 7219: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7220:0):     my ($r,$symb)=@_;
1.203     albertel 7221:     if (!$symb) {return '';}
1.324     albertel 7222:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7223:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7224:     if ( $env{'form.selectpage'} eq '' ||
                   7225: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7226: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7227: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7228: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7229: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7230: 	} 
1.257     albertel 7231: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7232: 	    $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 7233: 	} 
1.257     albertel 7234: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7235: 	    $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 7236: 	} 
                   7237:     } else {
1.596.2.12.2.  1(raebur 7238:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7239:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7240: 	$r->print('
1.596.2.12.2.  (raeburn 7241:): '.$warning.$bubbledbyhand.'
1.492     albertel 7242: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7243: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7244: ');
1.237     albertel 7245:     }
1.596.2.12.2.  1(raebur 7246:0):     $r->print("</form><br />");
1.203     albertel 7247:     return '';
                   7248: }
                   7249: 
1.423     albertel 7250: =pod
                   7251: 
                   7252: =item scantron_form_start
                   7253: 
1.424     albertel 7254:     html hidden input for remembering all selected grading options
                   7255: 
1.423     albertel 7256: =cut
                   7257: 
1.203     albertel 7258: sub scantron_form_start {
                   7259:     my ($max_bubble)=@_;
                   7260:     my $result= <<SCANTRONFORM;
                   7261: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7262:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7263:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7264:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7265:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7266:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7267:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7268:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7269:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7270:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7271: SCANTRONFORM
1.447     foxr     7272: 
                   7273:   my $line = 0;
                   7274:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7275:        my $chunk =
                   7276: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7277:        $chunk .=
                   7278: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7279:        $chunk .= 
                   7280:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7281:        $chunk .=
                   7282:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7283:3):        $chunk .=
                   7284:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7285:        $result .= $chunk;
                   7286:        $line++;
1.596.2.12.2.  6(raebur 7287:3):     }
1.203     albertel 7288:     return $result;
                   7289: }
                   7290: 
1.423     albertel 7291: =pod
                   7292: 
                   7293: =item scantron_validate_file
                   7294: 
1.596.2.6  raeburn  7295:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7296: 
                   7297:     Also processes any necessary information resets that need to
                   7298:     occur before validation begins (ignore previous corrections,
                   7299:     restarting the skipped records processing)
                   7300: 
1.423     albertel 7301: =cut
                   7302: 
1.157     albertel 7303: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7304:0):     my ($r,$symb) = @_;
1.157     albertel 7305:     if (!$symb) {return '';}
1.324     albertel 7306:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7307:     
1.596.2.12.2.  0(raebur 7308:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7309:     # them when doing the corrections reset
1.257     albertel 7310:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7311: 	&reset_skipping_status();
                   7312:     }
1.257     albertel 7313:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7314: 	&remember_current_skipped();
1.257     albertel 7315: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7316:     }
                   7317: 
1.257     albertel 7318:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7319: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7320: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7321: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7322: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7323:     }
1.200     albertel 7324: 
1.257     albertel 7325:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7326: 	&scantron_process_corrections($r);
                   7327:     }
1.503     raeburn  7328:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7329:     #get the student pick code ready
                   7330:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7331:     my $nav_error;
1.596.2.12.2.  9(raebur 7332:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7333:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7334:     if ($nav_error) {
                   7335:         $r->print(&navmap_errormsg());
                   7336:         return '';
                   7337:     }
1.203     albertel 7338:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7339:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7340:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7341:):     }
1.157     albertel 7342:     $r->print($result);
                   7343:     
1.334     albertel 7344:     my @validate_phases=( 'sequence',
                   7345: 			  'ID',
1.157     albertel 7346: 			  'CODE',
                   7347: 			  'doublebubble',
                   7348: 			  'missingbubbles');
1.257     albertel 7349:     if (!$env{'form.validatepass'}) {
                   7350: 	$env{'form.validatepass'} = 0;
1.157     albertel 7351:     }
1.257     albertel 7352:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7353: 
1.448     foxr     7354: 
1.157     albertel 7355:     my $stop=0;
                   7356:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7357: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7358: 	$r->rflush();
1.596.2.12.2.  6(raebur 7359:3): 
1.157     albertel 7360: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7361: 	{
                   7362: 	    no strict 'refs';
                   7363: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7364: 	}
                   7365:     }
                   7366:     if (!$stop) {
1.596.2.12.2.  1(raebur 7367:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7368: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7369:                   $warning.
                   7370:                   &mt('Perform verification for each student after storage of submissions?').
                   7371:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7372:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7373:                   ('&nbsp;'x3).'<label>'.
                   7374:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7375:                   '</label></span><br />'.
                   7376:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7377:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7378:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7379:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7380:     } else {
                   7381: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7382: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7383:     }
                   7384:     if ($stop) {
1.334     albertel 7385: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7386: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7387: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7388: 
1.596.2.12.2.  1(raebur 7389: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 7390: 	} else {
1.503     raeburn  7391:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7392: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7393:             } else {
1.539     riegler  7394:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7395:             }
1.492     albertel 7396: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7397: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7398: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7399: 	}
1.157     albertel 7400:     }
1.596.2.12.2.  1(raebur 7401:0):     $r->print(" </form><br />");
1.157     albertel 7402:     return '';
                   7403: }
                   7404: 
1.423     albertel 7405: 
                   7406: =pod
                   7407: 
                   7408: =item scantron_remove_file
                   7409: 
1.596.2.6  raeburn  7410:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7411:    scantron_original_<filename> is never removed
                   7412: 
                   7413: 
1.423     albertel 7414: =cut
                   7415: 
1.200     albertel 7416: sub scantron_remove_file {
1.192     albertel 7417:     my ($which)=@_;
1.257     albertel 7418:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7419:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7420:     my $file='scantron_';
1.200     albertel 7421:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7422: 	$file.=$which.'_';
1.192     albertel 7423:     } else {
                   7424: 	return 'refused';
                   7425:     }
1.257     albertel 7426:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7427:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7428: }
                   7429: 
1.423     albertel 7430: 
                   7431: =pod
                   7432: 
                   7433: =item scantron_remove_scan_data
                   7434: 
1.596.2.6  raeburn  7435:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7436:    data file.  (In the case that both the are doing skipped records we need
                   7437:    to remember the old skipped lines for the time being so that element
                   7438:    persists for a while.)
                   7439: 
1.423     albertel 7440: =cut
                   7441: 
1.200     albertel 7442: sub scantron_remove_scan_data {
1.257     albertel 7443:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7444:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7445:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7446:     my @todelete;
1.257     albertel 7447:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7448:     foreach my $key (@keys) {
                   7449: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7450: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7451: 		$key=~/remember_skipping/) {
                   7452: 		next;
                   7453: 	    }
1.192     albertel 7454: 	    push(@todelete,$key);
                   7455: 	}
                   7456:     }
1.200     albertel 7457:     my $result;
1.192     albertel 7458:     if (@todelete) {
1.491     albertel 7459: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7460: 				       \@todelete,$cdom,$cname);
                   7461:     } else {
                   7462: 	$result = 'ok';
1.192     albertel 7463:     }
                   7464:     return $result;
                   7465: }
                   7466: 
1.423     albertel 7467: 
                   7468: =pod
                   7469: 
                   7470: =item scantron_getfile
                   7471: 
1.596.2.6  raeburn  7472:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7473:     the scan_data hash
                   7474:   
                   7475:   Arguments:
                   7476:     None
                   7477: 
                   7478:   Returns:
                   7479:     2 hash references
                   7480: 
                   7481:      - first one has 
                   7482:          orig      -
                   7483:          corrected -
                   7484:          skipped   -  each of which points to an array ref of the specified
                   7485:                       file broken up into individual lines
                   7486:          count     - number of scanlines
                   7487:  
                   7488:      - second is the scan_data hash possible keys are
1.425     albertel 7489:        ($number refers to scanline numbered $number and thus the key affects
                   7490:         only that scanline
                   7491:         $bubline refers to the specific bubble line element and the aspects
                   7492:         refers to that specific bubble line element)
                   7493: 
                   7494:        $number.user - username:domain to use
                   7495:        $number.CODE_ignore_dup 
                   7496:                     - ignore the duplicate CODE error 
                   7497:        $number.useCODE
                   7498:                     - use the CODE in the scanline as is
                   7499:        $number.no_bubble.$bubline
                   7500:                     - it is valid that there is no bubbled in bubble
                   7501:                       at $number $bubline
                   7502:        remember_skipping
                   7503:                     - a frozen hash containing keys of $number and values
                   7504:                       of either 
                   7505:                         1 - we are on a 'do skipped records pass' and plan
                   7506:                             on processing this line
                   7507:                         2 - we are on a 'do skipped records pass' and this
                   7508:                             scanline has been marked to skip yet again
1.424     albertel 7509: 
1.423     albertel 7510: =cut
                   7511: 
1.157     albertel 7512: sub scantron_getfile {
1.200     albertel 7513:     #FIXME really would prefer a scantron directory
1.257     albertel 7514:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7515:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7516:     my $lines;
                   7517:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7518: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7519:     my %scanlines;
                   7520:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7521:     my $temp=$scanlines{'orig'};
                   7522:     $scanlines{'count'}=$#$temp;
                   7523: 
                   7524:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7525: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7526:     if ($lines eq '-1') {
                   7527: 	$scanlines{'corrected'}=[];
                   7528:     } else {
                   7529: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7530:     }
                   7531:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7532: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7533:     if ($lines eq '-1') {
                   7534: 	$scanlines{'skipped'}=[];
                   7535:     } else {
                   7536: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7537:     }
1.175     albertel 7538:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7539:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7540:     my %scan_data = @tmp;
                   7541:     return (\%scanlines,\%scan_data);
                   7542: }
                   7543: 
1.423     albertel 7544: =pod
                   7545: 
                   7546: =item lonnet_putfile
                   7547: 
1.424     albertel 7548:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7549: 
                   7550:  Arguments:
                   7551:    $contents - data to store
                   7552:    $filename - filename to store $contents into
                   7553: 
                   7554:  Returns:
                   7555:    result value from &Apache::lonnet::finishuserfileupload
                   7556: 
1.423     albertel 7557: =cut
                   7558: 
1.157     albertel 7559: sub lonnet_putfile {
                   7560:     my ($contents,$filename)=@_;
1.257     albertel 7561:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7562:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7563:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7564:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7565: 
                   7566: }
                   7567: 
1.423     albertel 7568: =pod
                   7569: 
                   7570: =item scantron_putfile
                   7571: 
1.596.2.6  raeburn  7572:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7573:     scan_data hash. (Does not modify the original version only the
                   7574:     corrected and skipped versions.
                   7575: 
                   7576:  Arguments:
                   7577:     $scanlines - hash ref that looks like the first return value from
                   7578:                  &scantron_getfile()
                   7579:     $scan_data - hash ref that looks like the second return value from
                   7580:                  &scantron_getfile()
                   7581: 
1.423     albertel 7582: =cut
                   7583: 
1.157     albertel 7584: sub scantron_putfile {
                   7585:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7586:     #FIXME really would prefer a scantron directory
1.257     albertel 7587:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7588:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7589:     if ($scanlines) {
                   7590: 	my $prefix='scantron_';
1.157     albertel 7591: # no need to update orig, shouldn't change
                   7592: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7593: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7594: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7595: 			$prefix.'corrected_'.
1.257     albertel 7596: 			$env{'form.scantron_selectfile'});
1.200     albertel 7597: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7598: 			$prefix.'skipped_'.
1.257     albertel 7599: 			$env{'form.scantron_selectfile'});
1.200     albertel 7600:     }
1.175     albertel 7601:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7602: }
                   7603: 
1.423     albertel 7604: =pod
                   7605: 
                   7606: =item scantron_get_line
                   7607: 
1.424     albertel 7608:    Returns the correct version of the scanline
                   7609: 
                   7610:  Arguments:
                   7611:     $scanlines - hash ref that looks like the first return value from
                   7612:                  &scantron_getfile()
                   7613:     $scan_data - hash ref that looks like the second return value from
                   7614:                  &scantron_getfile()
                   7615:     $i         - number of the requested line (starts at 0)
                   7616: 
                   7617:  Returns:
                   7618:    A scanline, (either the original or the corrected one if it
                   7619:    exists), or undef if the requested scanline should be
                   7620:    skipped. (Either because it's an skipped scanline, or it's an
                   7621:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7622:    pass.
                   7623: 
1.423     albertel 7624: =cut
                   7625: 
1.157     albertel 7626: sub scantron_get_line {
1.200     albertel 7627:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7628:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7629:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7630:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7631:     return $scanlines->{'orig'}[$i]; 
                   7632: }
                   7633: 
1.423     albertel 7634: =pod
                   7635: 
                   7636: =item scantron_todo_count
                   7637: 
1.424     albertel 7638:     Counts the number of scanlines that need processing.
                   7639: 
                   7640:  Arguments:
                   7641:     $scanlines - hash ref that looks like the first return value from
                   7642:                  &scantron_getfile()
                   7643:     $scan_data - hash ref that looks like the second return value from
                   7644:                  &scantron_getfile()
                   7645: 
                   7646:  Returns:
                   7647:     $count - number of scanlines to process
                   7648: 
1.423     albertel 7649: =cut
                   7650: 
1.200     albertel 7651: sub get_todo_count {
                   7652:     my ($scanlines,$scan_data)=@_;
                   7653:     my $count=0;
                   7654:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7655: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7656: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7657: 	$count++;
                   7658:     }
                   7659:     return $count;
                   7660: }
                   7661: 
1.423     albertel 7662: =pod
                   7663: 
                   7664: =item scantron_put_line
                   7665: 
1.596.2.6  raeburn  7666:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7667:     data file.
                   7668: 
                   7669:  Arguments:
                   7670:     $scanlines - hash ref that looks like the first return value from
                   7671:                  &scantron_getfile()
                   7672:     $scan_data - hash ref that looks like the second return value from
                   7673:                  &scantron_getfile()
                   7674:     $i         - line number to update
                   7675:     $newline   - contents of the updated scanline
                   7676:     $skip      - if true make the line for skipping and update the
                   7677:                  'skipped' file
                   7678: 
1.423     albertel 7679: =cut
                   7680: 
1.157     albertel 7681: sub scantron_put_line {
1.200     albertel 7682:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7683:     if ($skip) {
                   7684: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7685: 	&start_skipping($scan_data,$i);
1.157     albertel 7686: 	return;
                   7687:     }
                   7688:     $scanlines->{'corrected'}[$i]=$newline;
                   7689: }
                   7690: 
1.423     albertel 7691: =pod
                   7692: 
                   7693: =item scantron_clear_skip
                   7694: 
1.424     albertel 7695:    Remove a line from the 'skipped' file
                   7696: 
                   7697:  Arguments:
                   7698:     $scanlines - hash ref that looks like the first return value from
                   7699:                  &scantron_getfile()
                   7700:     $scan_data - hash ref that looks like the second return value from
                   7701:                  &scantron_getfile()
                   7702:     $i         - line number to update
                   7703: 
1.423     albertel 7704: =cut
                   7705: 
1.376     albertel 7706: sub scantron_clear_skip {
                   7707:     my ($scanlines,$scan_data,$i)=@_;
                   7708:     if (exists($scanlines->{'skipped'}[$i])) {
                   7709: 	undef($scanlines->{'skipped'}[$i]);
                   7710: 	return 1;
                   7711:     }
                   7712:     return 0;
                   7713: }
                   7714: 
1.423     albertel 7715: =pod
                   7716: 
                   7717: =item scantron_filter_not_exam
                   7718: 
1.424     albertel 7719:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7720:    filter out resources that are not marked as 'exam' mode
                   7721: 
1.423     albertel 7722: =cut
                   7723: 
1.334     albertel 7724: sub scantron_filter_not_exam {
                   7725:     my ($curres)=@_;
                   7726:     
                   7727:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7728: 	# if the user has asked to not have either hidden
                   7729: 	# or 'randomout' controlled resources to be graded
                   7730: 	# don't include them
                   7731: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7732: 	    && $curres->randomout) {
                   7733: 	    return 0;
                   7734: 	}
                   7735: 	return 1;
                   7736:     }
                   7737:     return 0;
                   7738: }
                   7739: 
1.423     albertel 7740: =pod
                   7741: 
                   7742: =item scantron_validate_sequence
                   7743: 
1.424     albertel 7744:     Validates the selected sequence, checking for resource that are
                   7745:     not set to exam mode.
                   7746: 
1.423     albertel 7747: =cut
                   7748: 
1.334     albertel 7749: sub scantron_validate_sequence {
                   7750:     my ($r,$currentphase) = @_;
                   7751: 
                   7752:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7753:     unless (ref($navmap)) {
                   7754:         $r->print(&navmap_errormsg());
                   7755:         return (1,$currentphase);
                   7756:     }
1.334     albertel 7757:     my (undef,undef,$sequence)=
                   7758: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7759: 
                   7760:     my $map=$navmap->getResourceByUrl($sequence);
                   7761: 
                   7762:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7763:                                     value="ignore" />');
                   7764:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7765: 	my @resources=
                   7766: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7767: 	if (@resources) {
1.596.2.12.2.  0(raebur 7768:2): 	    $r->print('<p class="LC_warning">'
                   7769:2):                .&mt('Some resources in the sequence currently are not set to'
                   7770:2):                    .' exam mode. Grading these resources currently may not'
                   7771:2):                    .' work correctly.')
                   7772:2):                .'</p>'
                   7773:2):             );
1.334     albertel 7774: 	    return (1,$currentphase);
                   7775: 	}
                   7776:     }
                   7777: 
                   7778:     return (0,$currentphase+1);
                   7779: }
                   7780: 
1.423     albertel 7781: 
                   7782: 
1.157     albertel 7783: sub scantron_validate_ID {
                   7784:     my ($r,$currentphase) = @_;
                   7785:     
                   7786:     #get student info
                   7787:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7788:     my %idmap=&username_to_idmap($classlist);
                   7789: 
                   7790:     #get scantron line setup
1.596.2.12.2.  9(raebur 7791:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7792:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7793: 
                   7794:     my $nav_error;
1.596.2.12.2.  (raeburn 7795:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7796:     if ($nav_error) {
                   7797:         $r->print(&navmap_errormsg());
                   7798:         return(1,$currentphase);
                   7799:     }
1.157     albertel 7800: 
                   7801:     my %found=('ids'=>{},'usernames'=>{});
                   7802:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7803: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7804: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7805: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7806: 						 $scan_data);
                   7807: 	my $id=$$scan_record{'scantron.ID'};
                   7808: 	my $found;
                   7809: 	foreach my $checkid (keys(%idmap)) {
                   7810: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7811: 	}
                   7812: 	if ($found) {
                   7813: 	    my $username=$idmap{$found};
                   7814: 	    if ($found{'ids'}{$found}) {
                   7815: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7816: 					 $line,'duplicateID',$found);
1.194     albertel 7817: 		return(1,$currentphase);
1.157     albertel 7818: 	    } elsif ($found{'usernames'}{$username}) {
                   7819: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7820: 					 $line,'duplicateID',$username);
1.194     albertel 7821: 		return(1,$currentphase);
1.157     albertel 7822: 	    }
1.186     albertel 7823: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7824: 	    $found{'ids'}{$found}++;
                   7825: 	    $found{'usernames'}{$username}++;
                   7826: 	} else {
                   7827: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7828: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7829: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7830: 		    &scantron_get_correction($r,$i,$scan_record,
                   7831: 					     \%scantron_config,
                   7832: 					     $line,'duplicateID',$username);
1.194     albertel 7833: 		    return(1,$currentphase);
1.157     albertel 7834: 		} elsif (!defined($username)) {
                   7835: 		    &scantron_get_correction($r,$i,$scan_record,
                   7836: 					     \%scantron_config,
                   7837: 					     $line,'incorrectID');
1.194     albertel 7838: 		    return(1,$currentphase);
1.157     albertel 7839: 		}
                   7840: 		$found{'usernames'}{$username}++;
                   7841: 	    } else {
                   7842: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7843: 					 $line,'incorrectID');
1.194     albertel 7844: 		return(1,$currentphase);
1.157     albertel 7845: 	    }
                   7846: 	}
                   7847:     }
                   7848: 
                   7849:     return (0,$currentphase+1);
                   7850: }
                   7851: 
1.423     albertel 7852: 
1.157     albertel 7853: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7854:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7855:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7856: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7857: #to show both the current line and the previous one and allow skipping
                   7858: #the previous one or the current one
                   7859: 
1.333     albertel 7860:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7861:         $r->print(
                   7862:             '<p class="LC_warning">'
                   7863:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7864:                 "<b>$error</b>",
                   7865:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7866:            ."</p> \n");
1.157     albertel 7867:     } else {
1.596.2.6  raeburn  7868:         $r->print(
                   7869:             '<p class="LC_warning">'
                   7870:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7871:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7872:            ."</p> \n");
                   7873:     }
                   7874:     my $message =
                   7875:         '<p>'
                   7876:        .&mt('The ID on the form is [_1]',
                   7877:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7878:        .'<br />'
1.596.2.12  raeburn  7879:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7880:             $$scan_record{'scantron.LastName'},
                   7881:             $$scan_record{'scantron.FirstName'})
                   7882:        .'</p>';
1.242     albertel 7883: 
1.157     albertel 7884:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7885:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7886:                            # Array populated for doublebubble or
                   7887:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7888:                            # to validate radio button checking   
                   7889: 
1.157     albertel 7890:     if ($error =~ /ID$/) {
1.186     albertel 7891: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7892: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7893: 		      "</p>\n");
1.157     albertel 7894: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7895: 	    $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 7896: 	}
1.242     albertel 7897: 	$r->print($message);
1.492     albertel 7898: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7899: 	$r->print("\n<ul><li> ");
                   7900: 	#FIXME it would be nice if this sent back the user ID and
                   7901: 	#could do partial userID matches
                   7902: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7903: 				       'scantron_username','scantron_domain'));
                   7904: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7905:3): 	$r->print("\n:\n".
1.257     albertel 7906: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7907: 
                   7908: 	$r->print('</li>');
1.186     albertel 7909:     } elsif ($error =~ /CODE$/) {
                   7910: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7911: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7912: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7913: 	    $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 7914: 	}
1.596.2.6  raeburn  7915:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7916:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7917:                  ."</p>\n");
1.242     albertel 7918: 	$r->print($message);
1.596.2.6  raeburn  7919: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7920: 	$r->print("\n<br /> ");
1.194     albertel 7921: 	my $i=0;
1.273     albertel 7922: 	if ($error eq 'incorrectCODE' 
                   7923: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7924: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7925: 	    if ($closest > 0) {
                   7926: 		foreach my $testcode (@{$closest}) {
                   7927: 		    my $checked='';
1.569     bisitz   7928: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7929: 		    $r->print("
                   7930:    <label>
1.569     bisitz   7931:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7932:        ".&mt("Use the similar CODE [_1] instead.",
                   7933: 	    "<b><tt>".$testcode."</tt></b>")."
                   7934:     </label>
                   7935:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7936: 		    $r->print("\n<br />");
                   7937: 		    $i++;
                   7938: 		}
1.194     albertel 7939: 	    }
                   7940: 	}
1.273     albertel 7941: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7942: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7943: 	    $r->print("
                   7944:     <label>
1.569     bisitz   7945:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7946:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7947: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7948:     </label>");
1.273     albertel 7949: 	    $r->print("\n<br />");
                   7950: 	}
1.194     albertel 7951: 
1.596.2.12.2.  1(raebur 7952:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7953: function change_radio(field) {
1.190     albertel 7954:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7955:     var i;
                   7956:     for (i=0;i<slct.length;i++) {
                   7957:         if (slct[i].value==field) { slct[i].checked=true; }
                   7958:     }
                   7959: }
                   7960: ENDSCRIPT
1.187     albertel 7961: 	my $href="/adm/pickcode?".
1.359     www      7962: 	   "form=".&escape("scantronupload").
                   7963: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7964: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7965: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7966: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7967: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7968: 	    $r->print("
                   7969:     <label>
                   7970:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7971:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7972: 	     "<a target='_blank' href='$href'>","</a>")."
                   7973:     </label> 
1.558     bisitz   7974:     ".&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 7975: 	    $r->print("\n<br />");
                   7976: 	}
1.492     albertel 7977: 	$r->print("
                   7978:     <label>
                   7979:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7980:        ".&mt("Use [_1] as the CODE.",
                   7981: 	     "</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 7982: 	$r->print("\n<br /><br />");
1.157     albertel 7983:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7984: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7985: 
                   7986: 	# The form field scantron_questions is acutally a list of line numbers.
                   7987: 	# represented by this form so:
                   7988: 
1.596.2.12.2.  6(raebur 7989:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7990:3):                                                 $respnumlookup,$startline);
1.497     foxr     7991: 
1.157     albertel 7992: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7993: 		  $line_list.'" />');
1.242     albertel 7994: 	$r->print($message);
1.492     albertel 7995: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7996: 	foreach my $question (@{$arg}) {
1.503     raeburn  7997: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7998:3):                                                    $scan_record, $error,
                   7999:3):                                                    $randomorder,$randompick,
                   8000:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8001:             push(@lines_to_correct,@linenums);
1.157     albertel 8002: 	}
1.503     raeburn  8003:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8004:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  8005: 	$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 8006: 	$r->print($message);
1.492     albertel 8007: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8008: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8009: 
1.503     raeburn  8010: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8011: 	# a list of question numbers. Therefore:
                   8012: 	#
                   8013: 	
1.596.2.12.2.  6(raebur 8014:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8015:3):                                                 $respnumlookup,$startline);
1.497     foxr     8016: 
1.157     albertel 8017: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8018: 		  $line_list.'" />');
1.157     albertel 8019: 	foreach my $question (@{$arg}) {
1.503     raeburn  8020: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 8021:3):                                                    $scan_record, $error,
                   8022:3):                                                    $randomorder,$randompick,
                   8023:3):                                                    $respnumlookup,$startline);
1.524     raeburn  8024:             push(@lines_to_correct,@linenums);
1.157     albertel 8025: 	}
1.503     raeburn  8026:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8027:     } else {
                   8028: 	$r->print("\n<ul>");
                   8029:     }
                   8030:     $r->print("\n</li></ul>");
1.497     foxr     8031: }
                   8032: 
1.503     raeburn  8033: sub verify_bubbles_checked {
                   8034:     my (@ansnums) = @_;
                   8035:     my $ansnumstr = join('","',@ansnums);
                   8036:     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 8037:6):     &js_escape(\$warning);
          1(raebur 8038:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8039: function verify_bubble_radio(form) {
                   8040:     var ansnumArray = new Array ("$ansnumstr");
                   8041:     var need_bubble_count = 0;
                   8042:     for (var i=0; i<ansnumArray.length; i++) {
                   8043:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8044:             var bubble_picked = 0; 
                   8045:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8046:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8047:                     bubble_picked = 1;
                   8048:                 }
                   8049:             }
                   8050:             if (bubble_picked == 0) {
                   8051:                 need_bubble_count ++;
                   8052:             }
                   8053:         }
                   8054:     }
                   8055:     if (need_bubble_count) {
                   8056:         alert("$warning");
                   8057:         return;
                   8058:     }
                   8059:     form.submit(); 
                   8060: }
                   8061: ENDSCRIPT
                   8062:     return $output;
                   8063: }
                   8064: 
1.497     foxr     8065: =pod
                   8066: 
                   8067: =item  questions_to_line_list
1.157     albertel 8068: 
1.497     foxr     8069: Converts a list of questions into a string of comma separated
                   8070: line numbers in the answer sheet used by the questions.  This is
                   8071: used to fill in the scantron_questions form field.
                   8072: 
                   8073:   Arguments:
                   8074:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 8075:3):      randomorder  - True if randomorder in use.
                   8076:3):      randompick   - True if randompick in use.
                   8077:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8078:3):                      for current line to question number used for same question
                   8079:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   8080:3):      startline    - Reference to hash where key is question number (0 is first)
                   8081:3):                     and key is number of first bubble line for current student
                   8082:3):                     or code-based randompick and/or randomorder.
1.497     foxr     8083: 
                   8084: =cut
                   8085: 
                   8086: 
                   8087: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 8088:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8089:     my @lines;
                   8090: 
1.503     raeburn  8091:     foreach my $item (@{$questions}) {
                   8092:         my $question = $item;
                   8093:         my ($first,$count,$last);
                   8094:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8095:             $question = $1;
                   8096:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 8097:3):             my $responsenum = $question-1;
                   8098:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8099:3):                 $responsenum = $respnumlookup->{$question-1};
                   8100:3):                 if (ref($startline) eq 'HASH') {
                   8101:3):                     $first = $startline->{$question-1} + 1;
                   8102:3):                 }
                   8103:3):             } else {
                   8104:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8105:3):             }
          7(raebur 8106:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8107:             my $subcount = 1;
                   8108:             while ($subcount<$subquestion) {
                   8109:                 $first += $subans[$subcount-1];
                   8110:                 $subcount ++;
                   8111:             }
                   8112:             $count = $subans[$subquestion-1];
                   8113:         } else {
1.596.2.12.2.  7(raebur 8114:3):             my $responsenum = $question-1;
                   8115:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8116:3):                 $responsenum = $respnumlookup->{$question-1};
                   8117:3):                 if (ref($startline) eq 'HASH') {
                   8118:3):                     $first = $startline->{$question-1} + 1;
                   8119:3):                 }
                   8120:3):             } else {
                   8121:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8122:3):             }
                   8123:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8124:         }
1.506     raeburn  8125:         $last = $first+$count-1;
1.503     raeburn  8126:         push(@lines, ($first..$last));
1.497     foxr     8127:     }
                   8128:     return join(',', @lines);
                   8129: }
                   8130: 
                   8131: =pod 
                   8132: 
                   8133: =item prompt_for_corrections
                   8134: 
                   8135: Prompts for a potentially multiline correction to the
                   8136: user's bubbling (factors out common code from scantron_get_correction
                   8137: for multi and missing bubble cases).
                   8138: 
                   8139:  Arguments:
                   8140:    $r           - Apache request object.
                   8141:    $question    - The question number to prompt for.
                   8142:    $scan_config - The scantron file configuration hash.
                   8143:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8144:    $error       - Type of error
1.596.2.12.2.  7(raebur 8145:3):    $randomorder - True if randomorder in use.
                   8146:3):    $randompick  - True if randompick in use.
                   8147:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8148:3):                     for current line to question number used for same question
                   8149:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8150:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8151:3):                   and value is number of first bubble line for current student
                   8152:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8153: 
                   8154:  Implicit inputs:
                   8155:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8156:                                   Numbered from 0 (but question numbers are from
                   8157:                                   1.
                   8158:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8159:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8160:                                   type problems render as separate sub-questions, 
1.503     raeburn  8161:                                   in exam mode. This hash contains a 
                   8162:                                   comma-separated list of the lines per 
                   8163:                                   sub-question.
1.510     raeburn  8164:    %responsetype_per_response   - essayresponse, formularesponse,
                   8165:                                   stringresponse, imageresponse, reactionresponse,
                   8166:                                   and organicresponse type problem parts can have
1.503     raeburn  8167:                                   multiple lines per response if the weight
                   8168:                                   assigned exceeds 10.  In this case, only
                   8169:                                   one bubble per line is permitted, but more 
                   8170:                                   than one line might contain bubbles, e.g.
                   8171:                                   bubbling of: line 1 - J, line 2 - J, 
                   8172:                                   line 3 - B would assign 22 points.  
1.497     foxr     8173: 
                   8174: =cut
                   8175: 
                   8176: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8177:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8178:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8179:     my ($current_line,$lines);
                   8180:     my @linenums;
                   8181:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8182:3):     my ($first,$responsenum);
1.503     raeburn  8183:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8184:         $question = $1;
                   8185:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8186:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8187:3):             $responsenum = $respnumlookup->{$question-1};
                   8188:3):             if (ref($startline) eq 'HASH') {
                   8189:3):                 $first = $startline->{$question-1};
                   8190:3):             }
                   8191:3):         } else {
                   8192:3):             $responsenum = $question-1;
          7(raebur 8193:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8194:3):         }
                   8195:3):         $current_line = $first + 1 ;
                   8196:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8197:         my $subcount = 1;
                   8198:         while ($subcount<$subquestion) {
                   8199:             $current_line += $subans[$subcount-1];
                   8200:             $subcount ++;
                   8201:         }
                   8202:         $lines = $subans[$subquestion-1];
                   8203:     } else {
1.596.2.12.2.  6(raebur 8204:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8205:3):             $responsenum = $respnumlookup->{$question-1};
                   8206:3):             if (ref($startline) eq 'HASH') {
                   8207:3):                 $first = $startline->{$question-1};
                   8208:3):             }
                   8209:3):         } else {
                   8210:3):             $responsenum = $question-1;
                   8211:3):             $first = $first_bubble_line{$responsenum};
                   8212:3):         }
                   8213:3):         $current_line = $first + 1;
                   8214:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8215:     }
1.497     foxr     8216:     if ($lines > 1) {
1.503     raeburn  8217:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8218:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8219:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8220:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8221:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8222:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8223:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8224: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  8225:         } else {
                   8226:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8227:         }
1.497     foxr     8228:     }
                   8229:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8230:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8231:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8232: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8233:         push(@linenums,$current_line);
1.497     foxr     8234: 	$current_line++;
                   8235:     }
                   8236:     if ($lines > 1) {
                   8237: 	$r->print("<hr /><br />");
                   8238:     }
1.503     raeburn  8239:     return @linenums;
1.157     albertel 8240: }
1.423     albertel 8241: 
                   8242: =pod
                   8243: 
                   8244: =item scantron_bubble_selector
                   8245:   
                   8246:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8247:    possibly showing the existing the selected bubbles if known
1.423     albertel 8248: 
                   8249:  Arguments:
                   8250:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8251:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8252:     $line        - Number of the line being displayed.
1.503     raeburn  8253:     $questionnum - Question number (may include subquestion)
                   8254:     $error       - Type of error.
1.497     foxr     8255:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8256: 
                   8257: =cut
                   8258: 
1.157     albertel 8259: sub scantron_bubble_selector {
1.503     raeburn  8260:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8261:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8262: 
                   8263:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8264:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8265:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8266:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8267:):             $max=$$scan_config{'BubblesPerRow'};
                   8268:):             if (($scmode eq 'number') && ($max > 10)) {
                   8269:):                 $max = 10;
                   8270:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8271:):                 $max = 26;
                   8272:):             }
                   8273:):         } else {
                   8274:):             $max = 10;
                   8275:):         }
                   8276:):     }
1.274     albertel 8277: 
1.157     albertel 8278:     my @alphabet=('A'..'Z');
1.503     raeburn  8279:     $r->print(&Apache::loncommon::start_data_table().
                   8280:               &Apache::loncommon::start_data_table_row());
                   8281:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8282:     for (my $i=0;$i<$max+1;$i++) {
                   8283: 	$r->print("\n".'<td align="center">');
                   8284: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8285: 	else { $r->print('&nbsp;'); }
                   8286: 	$r->print('</td>');
                   8287:     }
1.503     raeburn  8288:     $r->print(&Apache::loncommon::end_data_table_row().
                   8289:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8290:     for (my $i=0;$i<$max;$i++) {
                   8291: 	$r->print("\n".
                   8292: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8293: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8294:     }
1.503     raeburn  8295:     my $nobub_checked = ' ';
                   8296:     if ($error eq 'missingbubble') {
                   8297:         $nobub_checked = ' checked = "checked" ';
                   8298:     }
                   8299:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8300: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8301:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8302:               $line.'" value="'.$questionnum.'" /></td>');
                   8303:     $r->print(&Apache::loncommon::end_data_table_row().
                   8304:               &Apache::loncommon::end_data_table());
1.157     albertel 8305: }
                   8306: 
1.423     albertel 8307: =pod
                   8308: 
                   8309: =item num_matches
                   8310: 
1.424     albertel 8311:    Counts the number of characters that are the same between the two arguments.
                   8312: 
                   8313:  Arguments:
                   8314:    $orig - CODE from the scanline
                   8315:    $code - CODE to match against
                   8316: 
                   8317:  Returns:
                   8318:    $count - integer count of the number of same characters between the
                   8319:             two arguments
                   8320: 
1.423     albertel 8321: =cut
                   8322: 
1.194     albertel 8323: sub num_matches {
                   8324:     my ($orig,$code) = @_;
                   8325:     my @code=split(//,$code);
                   8326:     my @orig=split(//,$orig);
                   8327:     my $same=0;
                   8328:     for (my $i=0;$i<scalar(@code);$i++) {
                   8329: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8330:     }
                   8331:     return $same;
                   8332: }
                   8333: 
1.423     albertel 8334: =pod
                   8335: 
                   8336: =item scantron_get_closely_matching_CODEs
                   8337: 
1.424     albertel 8338:    Cycles through all CODEs and finds the set that has the greatest
                   8339:    number of same characters as the provided CODE
                   8340: 
                   8341:  Arguments:
                   8342:    $allcodes - hash ref returned by &get_codes()
                   8343:    $CODE     - CODE from the current scanline
                   8344: 
                   8345:  Returns:
                   8346:    2 element list
                   8347:     - first elements is number of how closely matching the best fit is 
                   8348:       (5 means best set has 5 matching characters)
                   8349:     - second element is an arrary ref containing the set of valid CODEs
                   8350:       that best fit the passed in CODE
                   8351: 
1.423     albertel 8352: =cut
                   8353: 
1.194     albertel 8354: sub scantron_get_closely_matching_CODEs {
                   8355:     my ($allcodes,$CODE)=@_;
                   8356:     my @CODEs;
                   8357:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8358: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8359:     }
                   8360: 
                   8361:     return ($#CODEs,$CODEs[-1]);
                   8362: }
                   8363: 
1.423     albertel 8364: =pod
                   8365: 
                   8366: =item get_codes
                   8367: 
1.424     albertel 8368:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8369:    set of remembered CODEs.
                   8370: 
                   8371:  Arguments:
                   8372:   $old_name - name of the set of remembered CODEs
                   8373:   $cdom     - domain of the course
                   8374:   $cnum     - internal course name
                   8375: 
                   8376:  Returns:
                   8377:   %allcodes - keys are the valid CODEs, values are all 1
                   8378: 
1.423     albertel 8379: =cut
                   8380: 
1.194     albertel 8381: sub get_codes {
1.280     foxr     8382:     my ($old_name, $cdom, $cnum) = @_;
                   8383:     if (!$old_name) {
                   8384: 	$old_name=$env{'form.scantron_CODElist'};
                   8385:     }
                   8386:     if (!$cdom) {
                   8387: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8388:     }
                   8389:     if (!$cnum) {
                   8390: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8391:     }
1.278     albertel 8392:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8393: 				    $cdom,$cnum);
                   8394:     my %allcodes;
                   8395:     if ($result{"type\0$old_name"} eq 'number') {
                   8396: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8397:     } else {
                   8398: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8399:     }
1.194     albertel 8400:     return %allcodes;
                   8401: }
                   8402: 
1.423     albertel 8403: =pod
                   8404: 
                   8405: =item scantron_validate_CODE
                   8406: 
1.424     albertel 8407:    Validates all scanlines in the selected file to not have any
                   8408:    invalid or underspecified CODEs and that none of the codes are
                   8409:    duplicated if this was requested.
                   8410: 
1.423     albertel 8411: =cut
                   8412: 
1.157     albertel 8413: sub scantron_validate_CODE {
                   8414:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8415:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8416:     if ($scantron_config{'CODElocation'} &&
                   8417: 	$scantron_config{'CODEstart'} &&
                   8418: 	$scantron_config{'CODElength'}) {
1.257     albertel 8419: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8420: 	    &FIXME_blow_up()
                   8421: 	}
                   8422:     } else {
                   8423: 	return (0,$currentphase+1);
                   8424:     }
                   8425:     
                   8426:     my %usedCODEs;
                   8427: 
1.194     albertel 8428:     my %allcodes=&get_codes();
1.186     albertel 8429: 
1.582     raeburn  8430:     my $nav_error;
1.596.2.12.2.  (raeburn 8431:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8432:     if ($nav_error) {
                   8433:         $r->print(&navmap_errormsg());
                   8434:         return(1,$currentphase);
                   8435:     }
1.447     foxr     8436: 
1.186     albertel 8437:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8438:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8439: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8440: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8441: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8442: 						 $scan_data);
                   8443: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8444: 	my $error=0;
1.224     albertel 8445: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8446: 	    &scantron_get_correction($r,$i,$scan_record,
                   8447: 				     \%scantron_config,
                   8448: 				     $line,'incorrectCODE',\%allcodes);
                   8449: 	    return(1,$currentphase);
                   8450: 	}
1.221     albertel 8451: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8452: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8453: 	    &scantron_get_correction($r,$i,$scan_record,
                   8454: 				     \%scantron_config,
1.194     albertel 8455: 				     $line,'incorrectCODE',\%allcodes);
                   8456: 	    return(1,$currentphase);
1.186     albertel 8457: 	}
1.214     albertel 8458: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8459: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8460: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8461: 	    &scantron_get_correction($r,$i,$scan_record,
                   8462: 				     \%scantron_config,
1.194     albertel 8463: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8464: 	    return(1,$currentphase);
1.186     albertel 8465: 	}
1.524     raeburn  8466: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8467:     }
1.157     albertel 8468:     return (0,$currentphase+1);
                   8469: }
                   8470: 
1.423     albertel 8471: =pod
                   8472: 
                   8473: =item scantron_validate_doublebubble
                   8474: 
1.424     albertel 8475:    Validates all scanlines in the selected file to not have any
                   8476:    bubble lines with multiple bubbles marked.
                   8477: 
1.423     albertel 8478: =cut
                   8479: 
1.157     albertel 8480: sub scantron_validate_doublebubble {
                   8481:     my ($r,$currentphase) = @_;
                   8482:     #get student info
                   8483:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8484:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8485:3):     my (undef,undef,$sequence)=
                   8486:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8487: 
                   8488:     #get scantron line setup
1.596.2.12.2.  9(raebur 8489:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8490:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8491:3): 
                   8492:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8493:3):     unless (ref($navmap)) {
                   8494:3):         $r->print(&navmap_errormsg());
                   8495:3):         return(1,$currentphase);
                   8496:3):     }
                   8497:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8498:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8499:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8500:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8501:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8502:3): 
1.583     raeburn  8503:     my $nav_error;
1.596.2.12.2.  6(raebur 8504:3):     if (ref($map)) {
                   8505:3):         $randomorder = $map->randomorder();
                   8506:3):         $randompick = $map->randompick();
          0(raebur 8507:2):         unless ($randomorder || $randompick) {
                   8508:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8509:2):                 if ($res->randomorder()) {
                   8510:2):                     $randomorder = 1;
                   8511:2):                 }
                   8512:2):                 if ($res->randompick()) {
                   8513:2):                     $randompick = 1;
                   8514:2):                 }
                   8515:2):                 last if ($randomorder || $randompick);
                   8516:2):             }
                   8517:2):         }
          6(raebur 8518:3):         if ($randomorder || $randompick) {
                   8519:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8520:3):             if ($nav_error) {
                   8521:3):                 $r->print(&navmap_errormsg());
                   8522:3):                 return(1,$currentphase);
                   8523:3):             }
                   8524:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8525:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8526:3):         }
                   8527:3):     } else {
                   8528:3):         $r->print(&navmap_errormsg());
                   8529:3):         return(1,$currentphase);
                   8530:3):     }
                   8531:3): 
          (raeburn 8532:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8533:     if ($nav_error) {
                   8534:         $r->print(&navmap_errormsg());
                   8535:         return(1,$currentphase);
                   8536:     }
1.447     foxr     8537: 
1.157     albertel 8538:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8539: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8540: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8541: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8542:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8543:3):                                                  $randompick,$sequence,\@master_seq,
                   8544:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8545:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8546: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8547: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8548: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8549:3): 				 $$scan_record{'scantron.doubleerror'},
                   8550:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8551:     	return (1,$currentphase);
                   8552:     }
                   8553:     return (0,$currentphase+1);
                   8554: }
                   8555: 
1.423     albertel 8556: 
1.503     raeburn  8557: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8558:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8559:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8560: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8561: 	&restore_bubble_lines();
1.257     albertel 8562: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8563:     }
1.330     albertel 8564: 
1.447     foxr     8565:     my (undef, undef, $sequence) =
1.257     albertel 8566: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8567: 
1.447     foxr     8568:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8569:     unless (ref($navmap)) {
                   8570:         if (ref($nav_error)) {
                   8571:             $$nav_error = 1;
                   8572:         }
1.591     raeburn  8573:         return;
1.582     raeburn  8574:     }
1.191     albertel 8575:     my $map=$navmap->getResourceByUrl($sequence);
                   8576:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8577:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8578: 
                   8579:     &Apache::lonxml::clear_problem_counter();
                   8580: 
1.557     raeburn  8581:     my $uname       = $env{'user.name'};
                   8582:     my $udom        = $env{'user.domain'};
1.435     foxr     8583:     my $cid         = $env{'request.course.id'};
                   8584:     my $total_lines = 0;
                   8585:     %bubble_lines_per_response = ();
1.447     foxr     8586:     %first_bubble_line         = ();
1.503     raeburn  8587:     %subdivided_bubble_lines   = ();
                   8588:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8589:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8590: 
1.447     foxr     8591:     my $response_number = 0;
                   8592:     my $bubble_line     = 0;
1.191     albertel 8593:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8594:3):         my $resid = $resource->id();
          (raeburn 8595:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8596:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8597:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8598: 	    foreach my $part_id (@{$parts}) {
                   8599:                 my $lines;
                   8600: 
                   8601: 	        # TODO - make this a persistent hash not an array.
                   8602: 
                   8603:                 # optionresponse, matchresponse and rankresponse type items 
                   8604:                 # render as separate sub-questions in exam mode.
                   8605:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8606:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8607:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8608:                     my ($numbub,$numshown);
                   8609:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8610:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8611:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8612:                         }
                   8613:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8614:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8615:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8616:                         }
                   8617:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8618:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8619:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8620:                         }
                   8621:                     }
                   8622:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8623:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8624:                     }
1.596.2.12.2.  (raeburn 8625:):                     my $bubbles_per_row =
                   8626:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8627:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8628:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8629:                         $inner_bubble_lines++;
                   8630:                     }
                   8631:                     for (my $i=0; $i<$numshown; $i++) {
                   8632:                         $subdivided_bubble_lines{$response_number} .= 
                   8633:                             $inner_bubble_lines.',';
                   8634:                     }
                   8635:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8636:                     $lines = $numshown * $inner_bubble_lines;
                   8637:                 } else {
                   8638:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8639:):                 }
1.542     raeburn  8640: 
                   8641:                 $first_bubble_line{$response_number} = $bubble_line;
                   8642: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8643:                 $responsetype_per_response{$response_number} = 
                   8644:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8645:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8646: 	        $response_number++;
                   8647: 
                   8648: 	        $bubble_line +=  $lines;
                   8649: 	        $total_lines +=  $lines;
                   8650: 	    }
                   8651:         }
                   8652:     }
1.552     raeburn  8653:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8654: 
                   8655:     &save_bubble_lines();
                   8656:     $env{'form.scantron_maxbubble'} =
                   8657: 	$total_lines;
                   8658:     return $env{'form.scantron_maxbubble'};
                   8659: }
1.523     raeburn  8660: 
1.596.2.12.2.  (raeburn 8661:): sub bubblesheet_bubbles_per_row {
                   8662:):     my ($scantron_config) = @_;
                   8663:):     my $bubbles_per_row;
                   8664:):     if (ref($scantron_config) eq 'HASH') {
                   8665:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8666:):     }
                   8667:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8668:):         $bubbles_per_row = 10;
                   8669:):     }
                   8670:):     return $bubbles_per_row;
                   8671:): }
                   8672:): 
1.157     albertel 8673: sub scantron_validate_missingbubbles {
                   8674:     my ($r,$currentphase) = @_;
                   8675:     #get student info
                   8676:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8677:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8678:3):     my (undef,undef,$sequence)=
                   8679:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8680: 
                   8681:     #get scantron line setup
1.596.2.12.2.  9(raebur 8682:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8683:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8684:3): 
                   8685:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8686:3):     unless (ref($navmap)) {
                   8687:3):         $r->print(&navmap_errormsg());
                   8688:3):         return(1,$currentphase);
                   8689:3):     }
                   8690:3): 
                   8691:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8692:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8693:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8694:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8695:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8696:3): 
1.582     raeburn  8697:     my $nav_error;
1.596.2.12.2.  6(raebur 8698:3):     if (ref($map)) {
                   8699:3):         $randomorder = $map->randomorder();
                   8700:3):         $randompick = $map->randompick();
          0(raebur 8701:2):         unless ($randomorder || $randompick) {
                   8702:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8703:2):                 if ($res->randomorder()) {
                   8704:2):                     $randomorder = 1;
                   8705:2):                 }
                   8706:2):                 if ($res->randompick()) {
                   8707:2):                     $randompick = 1;
                   8708:2):                 }
                   8709:2):                 last if ($randomorder || $randompick);
                   8710:2):             }
                   8711:2):         }
          7(raebur 8712:3):         if ($randomorder || $randompick) {
                   8713:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8714:3):             if ($nav_error) {
                   8715:3):                 $r->print(&navmap_errormsg());
                   8716:3):                 return(1,$currentphase);
                   8717:3):             }
                   8718:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8719:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8720:3):         }
          6(raebur 8721:3):     } else {
                   8722:3):         $r->print(&navmap_errormsg());
          7(raebur 8723:3):         return(1,$currentphase);
          6(raebur 8724:3):     }
                   8725:3): 
                   8726:3): 
          (raeburn 8727:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8728:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8729:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8730:         return(1,$currentphase);
                   8731:     }
1.596.2.12.2.  6(raebur 8732:3): 
1.157     albertel 8733:     if (!$max_bubble) { $max_bubble=2**31; }
                   8734:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8735: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8736: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8737:3):         my $scan_record =
                   8738:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8739:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8740:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8741:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8742: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8743: 	my @to_correct;
1.470     foxr     8744: 	
                   8745: 	# Probably here's where the error is...
                   8746: 
1.157     albertel 8747: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8748:             my $lastbubble;
                   8749:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8750:3):                 my $question = $1;
                   8751:3):                 my $subquestion = $2;
                   8752:3):                 my ($first,$responsenum);
                   8753:3):                 if ($randomorder || $randompick) {
                   8754:3):                     $responsenum = $respnumlookup{$question-1};
                   8755:3):                     $first = $startline{$question-1};
                   8756:3):                 } else {
                   8757:3):                     $responsenum = $question-1;
                   8758:3):                     $first = $first_bubble_line{$responsenum};
                   8759:3):                 }
                   8760:3):                 if (!defined($first)) { next; }
          7(raebur 8761:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8762:3):                 my $subcount = 1;
                   8763:3):                 while ($subcount<$subquestion) {
                   8764:3):                     $first += $subans[$subcount-1];
                   8765:3):                     $subcount ++;
                   8766:3):                 }
                   8767:3):                 my $count = $subans[$subquestion-1];
                   8768:3):                 $lastbubble = $first + $count;
1.505     raeburn  8769:             } else {
1.596.2.12.2.  6(raebur 8770:3):                 my ($first,$responsenum);
                   8771:3):                 if ($randomorder || $randompick) {
                   8772:3):                     $responsenum = $respnumlookup{$missing-1};
                   8773:3):                     $first = $startline{$missing-1};
                   8774:3):                 } else {
                   8775:3):                     $responsenum = $missing-1;
                   8776:3):                     $first = $first_bubble_line{$responsenum};
                   8777:3):                 }
                   8778:3):                 if (!defined($first)) { next; }
                   8779:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8780:             }
                   8781:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8782: 	    push(@to_correct,$missing);
                   8783: 	}
                   8784: 	if (@to_correct) {
                   8785: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8786:3): 				     $line,'missingbubble',\@to_correct,
                   8787:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8788:3):                                      \%startline);
1.157     albertel 8789: 	    return (1,$currentphase);
                   8790: 	}
                   8791: 
                   8792:     }
                   8793:     return (0,$currentphase+1);
                   8794: }
                   8795: 
1.596.2.12.2.  (raeburn 8796:): sub hand_bubble_option {
                   8797:):     my (undef, undef, $sequence) =
                   8798:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8799:):     return if ($sequence eq '');
                   8800:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8801:):     unless (ref($navmap)) {
                   8802:):         return;
                   8803:):     }
                   8804:):     my $needs_hand_bubbles;
                   8805:):     my $map=$navmap->getResourceByUrl($sequence);
                   8806:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8807:):     foreach my $res (@resources) {
                   8808:):         if (ref($res)) {
                   8809:):             if ($res->is_problem()) {
                   8810:):                 my $partlist = $res->parts();
                   8811:):                 foreach my $part (@{ $partlist }) {
                   8812:):                     my @types = $res->responseType($part);
                   8813:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8814:):                         $needs_hand_bubbles = 1;
                   8815:):                         last;
                   8816:):                     }
                   8817:):                 }
                   8818:):             }
                   8819:):         }
                   8820:):     }
                   8821:):     if ($needs_hand_bubbles) {
          9(raebur 8822:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8823:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8824:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8825:):                &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 />').
                   8826:):                '<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 8827:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8828:):     }
                   8829:):     return;
                   8830:): }
1.423     albertel 8831: 
1.82      albertel 8832: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8833:0):     my ($r,$symb) = @_;
1.513     foxr     8834: 
1.257     albertel 8835:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8836:     if (!$symb) {
                   8837: 	return '';
                   8838:     }
1.324     albertel 8839:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8840: 
1.596.2.12.2.  9(raebur 8841:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8842:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8843:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8844:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8845:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8846:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8847:     unless (ref($navmap)) {
                   8848:         $r->print(&navmap_errormsg());
                   8849:         return '';
1.596.2.12.2.  6(raebur 8850:3):     }
1.83      albertel 8851:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8852:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
          0(raebur 8853:2):         %grader_randomlists_by_symb,%symb_for_examcode);
          1(raebur 8854:2):     if (ref($map)) {
                   8855:2):         $randomorder = $map->randomorder();
          6(raebur 8856:3):         $randompick = $map->randompick();
          0(raebur 8857:2):         unless ($randomorder || $randompick) {
                   8858:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   8859:2):                 if ($res->randomorder()) {
                   8860:2):                     $randomorder = 1;
                   8861:2):                 }
                   8862:2):                 if ($res->randompick()) {
                   8863:2):                     $randompick = 1;
                   8864:2):                 }
                   8865:2):                 last if ($randomorder || $randompick);
                   8866:2):             }
                   8867:2):         }
          6(raebur 8868:3):     } else {
                   8869:3):         $r->print(&navmap_errormsg());
                   8870:3):         return '';
          1(raebur 8871:2):     }
          6(raebur 8872:3):     my $nav_error;
1.83      albertel 8873:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8874:3):     if ($randomorder || $randompick) {
          0(raebur 8875:2):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource,1,\%symb_for_examcode);
          6(raebur 8876:3):         if ($nav_error) {
                   8877:3):             $r->print(&navmap_errormsg());
                   8878:3):             return '';
1.586     raeburn  8879:         }
                   8880:     }
1.596.2.12.2.  6(raebur 8881:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8882:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8883: 
1.554     raeburn  8884:     my ($uname,$udom);
1.82      albertel 8885:     my $result= <<SCANTRONFORM;
1.81      albertel 8886: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8887:   <input type="hidden" name="command" value="scantron_configphase" />
                   8888:   $default_form_data
                   8889: SCANTRONFORM
1.82      albertel 8890:     $r->print($result);
                   8891: 
                   8892:     my @delayqueue;
1.542     raeburn  8893:     my (%completedstudents,%scandata);
1.140     albertel 8894:     
1.520     www      8895:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8896:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8897:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 8898:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8899:     $r->print('<br />');
1.140     albertel 8900:     my $start=&Time::HiRes::time();
1.158     albertel 8901:     my $i=-1;
1.542     raeburn  8902:     my $started;
1.447     foxr     8903: 
1.596.2.12.2.  (raeburn 8904:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8905:     if ($nav_error) {
                   8906:         $r->print(&navmap_errormsg());
                   8907:         return '';
                   8908:     }
                   8909: 
1.513     foxr     8910:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8911:     # the user and return.
                   8912: 
                   8913:     if ($ssi_error) {
                   8914: 	$r->print("</form>");
                   8915: 	&ssi_print_error($r);
1.520     www      8916:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8917: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8918:     }
1.447     foxr     8919: 
1.596.2.12.2.  9(raebur 8920:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8921:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8922:3):     my %orderedforcode;
1.542     raeburn  8923: 
1.157     albertel 8924:     while ($i<$scanlines->{'count'}) {
                   8925:  	($uname,$udom)=('','');
                   8926:  	$i++;
1.200     albertel 8927:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8928:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8929: 	if ($started) {
1.596.2.12.2.  1(raebur 8930:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8931: 	}
                   8932: 	$started=1;
1.596.2.12.2.  6(raebur 8933:3):         my %respnumlookup = ();
                   8934:3):         my %startline = ();
                   8935:3):         my $total;
1.157     albertel 8936:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8937:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8938:3):                                                  $randompick,$sequence,\@master_seq,
                   8939:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8940:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8941:3):                                                  \$total);
1.157     albertel 8942:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8943:  					      \%idmap,$i)) {
                   8944:   	    &scantron_add_delay(\@delayqueue,$line,
                   8945:  				'Unable to find a student that matches',1);
                   8946:  	    next;
                   8947:   	}
                   8948:  	if (exists $completedstudents{$uname}) {
                   8949:  	    &scantron_add_delay(\@delayqueue,$line,
                   8950:  				'Student '.$uname.' has multiple sheets',2);
                   8951:  	    next;
                   8952:  	}
1.596.2.12.2.  1(raebur 8953:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8954:2):         my $user = $uname.':'.$usec;
1.157     albertel 8955:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8956: 
1.596.2.12.2.  1(raebur 8957:2):         my $scancode;
                   8958:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8959:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8960:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8961:2):         } else {
                   8962:2):             $scancode = '';
                   8963:2):         }
                   8964:2): 
                   8965:2):         my @mapresources = @resources;
          6(raebur 8966:3):         if ($randomorder || $randompick) {
          1(raebur 8967:2):             @mapresources =
          6(raebur 8968:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8969:3):                              \%orderedforcode);
          1(raebur 8970:2):         }
1.586     raeburn  8971:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8972:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8973:             my $ressymb;
                   8974:             if (ref($resource)) {
                   8975:                 $ressymb = $resource->symb();
                   8976:             } else {
                   8977:                 $res_error = 1;
                   8978:                 last;
                   8979:             }
1.557     raeburn  8980:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8981:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8982:7):                 my $currcode;
                   8983:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8984:7):                     $currcode = $scancode;
                   8985:7):                 }
1.557     raeburn  8986:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8987:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8988:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8989:7):                                               $currcode);
1.557     raeburn  8990:                 $partids_by_symb{$ressymb} = $parts;
                   8991:             } else {
                   8992:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8993:             }
1.554     raeburn  8994:         }
                   8995: 
1.586     raeburn  8996:         if ($res_error) {
                   8997:             &scantron_add_delay(\@delayqueue,$line,
                   8998:                                 'An error occurred while grading student '.$uname,2);
                   8999:             next;
                   9000:         }
                   9001: 
1.330     albertel 9002: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9003:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9004: 
                   9005: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9006: 	    &scantron_putfile($scanlines,$scan_data);
                   9007: 	}
1.161     albertel 9008: 	
1.542     raeburn  9009:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9010:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 9011:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   9012:3):                                    \%respnumlookup,\%startline) 
                   9013:3):             eq 'ssi_error') {
1.542     raeburn  9014:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9015:             $r->print("</form>");
                   9016:             &ssi_print_error($r);
                   9017:             &Apache::lonnet::remove_lock($lock);
                   9018:             return '';      # Why return ''?  Beats me.
                   9019:         }
1.513     foxr     9020: 
1.596.2.12.2.  6(raebur 9021:3):         if (($scancode) && ($randomorder || $randompick)) {
          0(raebur 9022:2):             foreach my $key (keys(%symb_for_examcode)) {
                   9023:2):                 my $symb_in_map = $symb_for_examcode{$key};
                   9024:2):                 if ($symb_in_map ne '') {
                   9025:2):                     my $parmresult =
                   9026:2):                         &Apache::lonparmset::storeparm_by_symb($symb_in_map,
                   9027:2):                                                                '0_examcode',2,$scancode,
                   9028:2):                                                                'string_examcode',$uname,
                   9029:2):                                                                $udom);
                   9030:2):                 }
                   9031:2):             }
          6(raebur 9032:3):         }
1.140     albertel 9033: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9034:         if ($env{'form.verifyrecord'}) {
                   9035:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 9036:3):             if ($randompick) {
                   9037:3):                 if ($total) {
                   9038:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   9039:3):                 }
                   9040:3):             }
                   9041:3): 
1.542     raeburn  9042:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9043:             chomp($studentdata);
                   9044:             $studentdata =~ s/\r$//;
                   9045:             my $studentrecord = '';
                   9046:             my $counter = -1;
1.596.2.12.2.  1(raebur 9047:2):             foreach my $resource (@mapresources) {
1.554     raeburn  9048:                 my $ressymb = $resource->symb();
1.542     raeburn  9049:                 ($counter,my $recording) =
                   9050:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9051:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9052:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9053:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9054:                 $studentrecord .= $recording;
                   9055:             }
                   9056:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9057:                 &Apache::lonxml::clear_problem_counter();
                   9058:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 9059:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 9060:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   9061:3):                                            \%respnumlookup,\%startline)
                   9062:3):                     eq 'ssi_error') {
1.554     raeburn  9063:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9064:                     $r->print("</form>");
                   9065:                     &ssi_print_error($r);
                   9066:                     &Apache::lonnet::remove_lock($lock);
                   9067:                     delete($completedstudents{$uname});
                   9068:                     return '';
                   9069:                 }
1.542     raeburn  9070:                 $counter = -1;
                   9071:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 9072:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  9073:                     my $ressymb = $resource->symb();
1.542     raeburn  9074:                     ($counter,my $recording) =
                   9075:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9076:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 9077:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   9078:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   9079:3):                                                  \%startline);
1.542     raeburn  9080:                     $studentrecord .= $recording;
                   9081:                 }
                   9082:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  9083:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9084:                     if ($scancode eq '') {
1.596.2.6  raeburn  9085:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9086:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9087:                     } else {
1.596.2.6  raeburn  9088:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9089:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9090:                     }
                   9091:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9092:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9093:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9094:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9095:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9096:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 9097:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9098:                               &Apache::loncommon::end_data_table_row().
                   9099:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  9100:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 9101:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9102:                               &Apache::loncommon::end_data_table_row().
                   9103:                               &Apache::loncommon::end_data_table().'</p>');
                   9104:                 } else {
                   9105:                     $r->print('<br /><span class="LC_warning">'.
                   9106:                              &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 />'.
                   9107:                              &mt("As a consequence, this user's submission history records two tries.").
                   9108:                                  '</span><br />');
                   9109:                 }
                   9110:             }
                   9111:         }
1.543     raeburn  9112:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9113:     } continue {
1.330     albertel 9114: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9115: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9116:     }
1.140     albertel 9117:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9118:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9119: #    my $lasttime = &Time::HiRes::time()-$start;
                   9120: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9121: 
1.200     albertel 9122:     $r->print("</form>");
1.157     albertel 9123:     return '';
1.75      albertel 9124: }
1.157     albertel 9125: 
1.557     raeburn  9126: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 9127:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9128:):         $bubbles_per_row) = @_;
1.557     raeburn  9129:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9130:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9131:         foreach my $resource (@{$resources}) {
                   9132:             my $ressymb = $resource->symb();
                   9133:             my ($analysis,$parts) =
                   9134:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 9135:):                                           $env{'user.name'},$env{'user.domain'},
                   9136:):                                           1,$bubbles_per_row);
1.557     raeburn  9137:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9138:             if (ref($analysis) eq 'HASH') {
                   9139:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9140:                     $grader_randomlists_by_symb->{$ressymb} =
                   9141:                         $analysis->{'parts_withrandomlist'};
                   9142:                 }
                   9143:             }
                   9144:         }
                   9145:     }
                   9146:     return;
                   9147: }
                   9148: 
1.596.2.12.2.  1(raebur 9149:2): =pod
                   9150:2): 
                   9151:2): =item users_order
                   9152:2): 
                   9153:2):   Returns array of resources in current map, ordered based on either CODE,
                   9154:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9155:2):   "NAMEd" exam.
                   9156:2): 
          6(raebur 9157:3):   Should be used when randomorder and/or randompick applied when the 
                   9158:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9159:3):   for the version of the exam the student received.
          1(raebur 9160:2): 
                   9161:2): =cut
                   9162:2): 
                   9163:2): sub users_order  {
          6(raebur 9164:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9165:2):     my @mapresources;
          6(raebur 9166:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9167:2):         return @mapresources;
                   9168:2):     }
          6(raebur 9169:3):     if ($scancode) {
                   9170:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9171:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9172:3):         } else {
                   9173:3):             $env{'form.CODE'} = $scancode;
                   9174:3):             my $actual_seq =
                   9175:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9176:3):                                                                $master_seq,
                   9177:3):                                                                $user,$scancode,1);
                   9178:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9179:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9180:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9181:3):                     if (@mapresources > 0) {
                   9182:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9183:3):                     }
                   9184:3):                 }
                   9185:3):             }
                   9186:3):             delete($env{'form.CODE'});
          1(raebur 9187:2):         }
                   9188:2):     } else {
                   9189:2):         my $actual_seq =
                   9190:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9191:2):                                                            $master_seq,
          5(raebur 9192:3):                                                            $user,undef,1);
          1(raebur 9193:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9194:2):             @mapresources =
                   9195:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9196:2):         }
          6(raebur 9197:3):     }
                   9198:3):     return @mapresources;
          1(raebur 9199:2): }
                   9200:2): 
1.542     raeburn  9201: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9202:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9203:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9204:3):     my $uselookup = 0;
                   9205:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9206:3):         (ref($startline) eq 'HASH')) {
                   9207:3):         $uselookup = 1;
                   9208:3):     }
                   9209:3): 
1.554     raeburn  9210:     if (ref($resources) eq 'ARRAY') {
                   9211:         my $count = 0;
                   9212:         foreach my $resource (@{$resources}) {
                   9213:             my $ressymb = $resource->symb();
                   9214:             my %form = ('submitted'      => 'scantron',
                   9215:                         'grade_target'   => 'grade',
                   9216:                         'grade_username' => $uname,
                   9217:                         'grade_domain'   => $udom,
                   9218:                         'grade_courseid' => $env{'request.course.id'},
                   9219:                         'grade_symb'     => $ressymb,
                   9220:                         'CODE'           => $scancode
                   9221:                        );
1.596.2.12.2.  (raeburn 9222:):             if ($bubbles_per_row ne '') {
                   9223:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9224:):             }
                   9225:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9226:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9227:):             }
1.554     raeburn  9228:             if (ref($parts) eq 'HASH') {
                   9229:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9230:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9231:3):                         if ($uselookup) {
                   9232:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9233:3):                         } else {
                   9234:3):                             $form{'scantron_questnum_start.'.$part} =
                   9235:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9236:3):                         }
1.554     raeburn  9237:                         $count++;
                   9238:                     }
                   9239:                 }
                   9240:             }
                   9241:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9242:             return 'ssi_error' if ($ssi_error);
                   9243:             last if (&Apache::loncommon::connection_aborted($r));
                   9244:         }
1.542     raeburn  9245:     }
                   9246:     return;
                   9247: }
                   9248: 
1.157     albertel 9249: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9250:0):     my ($r,$symb) = @_;
1.565     raeburn  9251:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9252:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9253:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9254:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9255:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9256: 							  'domainid',
1.565     raeburn  9257: 							  'coursename',$dom);
                   9258:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9259:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9260:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9261:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9262:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9263:     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 9264:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9265:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9266:     function checkUpload(formname) {
                   9267: 	if (formname.upfile.value == "") {
1.579     raeburn  9268: 	    alert("'.$nofile_alert.'");
1.157     albertel 9269: 	    return false;
                   9270: 	}
1.565     raeburn  9271:         if (formname.courseid.value == "") {
1.579     raeburn  9272:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9273:             return false;
                   9274:         }
1.157     albertel 9275: 	formname.submit();
                   9276:     }
1.565     raeburn  9277: 
                   9278:     function ToSyllabus() {
                   9279:         var cdom = '."'$dom'".';
                   9280:         var cnum = document.rules.courseid.value;
                   9281:         if (cdom == "" || cdom == null) {
                   9282:             return;
                   9283:         }
                   9284:         if (cnum == "" || cnum == null) {
                   9285:            return;
                   9286:         }
                   9287:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9288:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9289:         return;
                   9290:     }
                   9291: 
1.596.2.12.2.  9(raebur 9292:9):     '.$formatjs.'
                   9293:9): '));
                   9294:9):     $r->print('
1.596.2.4  raeburn  9295: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9296: 
1.492     albertel 9297: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9298: '.$default_form_data.
                   9299:   &Apache::lonhtmlcommon::start_pick_box().
                   9300:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9301:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9302:   &Apache::lonhtmlcommon::row_closure().
                   9303:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9304:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9305:   &Apache::lonhtmlcommon::row_closure().
                   9306:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9307:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9308:9):   &Apache::lonhtmlcommon::row_closure());
                   9309:9):     if ($formatoptions) {
                   9310:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9311:9):                   &Apache::lonhtmlcommon::row_closure());
                   9312:9):     }
                   9313:9):     $r->print(
1.565     raeburn  9314:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9315:   '<input type="file" name="upfile" size="50" />'.
                   9316:   &Apache::lonhtmlcommon::row_closure(1).
                   9317:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9318: 
1.492     albertel 9319: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9320: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9321: </form>
1.492     albertel 9322: ');
1.157     albertel 9323:     return '';
                   9324: }
                   9325: 
1.596.2.12.2.  9(raebur 9326:9): sub scantron_upload_dataformat {
                   9327:9):     my ($dom) = @_;
                   9328:9):     my ($formatoptions,$formattitle,$formatjs);
                   9329:9):     $formatjs = <<'END';
                   9330:9): function toggleScantab(form) {
                   9331:9):    return;
                   9332:9): }
                   9333:9): END
                   9334:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9335:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9336:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9337:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9338:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9339:9):                     (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'}})) {
                   9342:9):                             my ($onclick,$formatextra,$singleline);
                   9343:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9344:9):                             my $count = 0;
                   9345:9):                             foreach my $line (@lines) {
                   9346:9):                                 next if ($line =~ /^#/);
                   9347:9):                                 $singleline = $line;
                   9348:9):                                 $count ++;
                   9349:9):                             }
                   9350:9):                             if ($count > 1) {
                   9351:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9352:9):                                                '<span class="LC_nobreak">'.
          4(raebur 9353:0):                                                &mt('Bubblesheet type').':&nbsp;'.
          9(raebur 9354:9):                                                &scantron_scantab().'</span></div>';
                   9355:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9356:9):                                 $formatjs = <<"END";
                   9357:9): function toggleScantab(form) {
                   9358:9):     var divid = 'bubbletype';
                   9359:9):     if (document.getElementById(divid)) {
                   9360:9):         var radioname = 'fileformat';
                   9361:9):         var num = form.elements[radioname].length;
                   9362:9):         if (num) {
                   9363:9):             for (var i=0; i<num; i++) {
                   9364:9):                 if (form.elements[radioname][i].checked) {
                   9365:9):                     var chosen = form.elements[radioname][i].value;
                   9366:9):                     if (chosen == 'dat') {
                   9367:9):                         document.getElementById(divid).style.display = 'none';
                   9368:9):                     } else if (chosen == 'csv') {
                   9369:9):                         document.getElementById(divid).style.display = 'block';
                   9370:9):                     }
                   9371:9):                 }
                   9372:9):             }
                   9373:9):         }
                   9374:9):     }
                   9375:9):     return;
                   9376:9): }
                   9377:9): 
                   9378:9): END
                   9379:9):                             } elsif ($count == 1) {
                   9380:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9381:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9382:9):                             }
                   9383:9):                             $formattitle = &mt('File format');
                   9384:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9385:9):                                              &mt('Plain Text (no delimiters)').
                   9386:9):                                              '</label>'.('&nbsp;'x2).
                   9387:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9388:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9389:9):                         }
                   9390:9):                     }
                   9391:9):                 }
                   9392:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9393:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9394:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9395:9):                         $formattitle = &mt('Bubblesheet type');
                   9396:9):                         $formatoptions = &scantron_scantab();
                   9397:9):                     }
                   9398:9):                 }
                   9399:9):             }
                   9400:9):         }
                   9401:9):     }
                   9402:9):     return ($formatoptions,$formattitle,$formatjs);
                   9403:9): }
1.423     albertel 9404: 
1.157     albertel 9405: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9406:0):     my ($r,$symb) = @_;
1.182     albertel 9407:     my $doanotherupload=
                   9408: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9409: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9410: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9411: 	'</form>'."\n";
1.257     albertel 9412:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9413: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9414: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9415: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9416:0):         unless ($symb) {
1.182     albertel 9417: 	    $r->print($doanotherupload);
                   9418: 	}
1.162     albertel 9419: 	return '';
                   9420:     }
1.257     albertel 9421:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9422:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9423:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9424:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9425:3):         $r->print(
                   9426:3):             &Apache::lonhtmlcommon::confirm_success(
                   9427:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9428:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9429:     } else {
1.596.2.12.2.  9(raebur 9430:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9431:9):         my $parser;
                   9432:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9433:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9434:9):                 my $is_csv;
                   9435:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9436:9):                 if (@possibles > 1) {
                   9437:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9438:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9439:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9440:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9441:9):                                     $is_csv = 1;
                   9442:9):                                 }
                   9443:9):                             }
                   9444:9):                         }
                   9445:9):                     }
                   9446:9):                 } elsif (@possibles == 1) {
                   9447:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9448:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9449:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9450:9):                                 $is_csv = 1;
                   9451:9):                             }
                   9452:9):                         }
                   9453:9):                     }
                   9454:9):                 }
                   9455:9):                 if ($is_csv) {
                   9456:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9457:9):                 }
                   9458:9):             }
                   9459:9):         }
                   9460:9):         my $result =
                   9461:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9462:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9463: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9464:3):             $r->print(
                   9465:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9466:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9467:3):                         (length($env{'form.upfile'})-1),
                   9468:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9469:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9470:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9471:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9472: 	} else {
1.596.2.12.2.  5(raebur 9473:3):             $r->print(
                   9474:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9475:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9476:3):                           $result,
1.568     raeburn  9477: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9478: 	}
                   9479:     }
1.174     albertel 9480:     if ($symb) {
1.596.2.12.2.  1(raebur 9481:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9482:     } else {
1.182     albertel 9483: 	$r->print($doanotherupload);
1.174     albertel 9484:     }
1.157     albertel 9485:     return '';
                   9486: }
                   9487: 
1.567     raeburn  9488: sub validate_uploaded_scantron_file {
                   9489:     my ($cdom,$cname,$fname) = @_;
                   9490:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9491:     my @lines;
                   9492:     if ($scanlines ne '-1') {
                   9493:         @lines=split("\n",$scanlines,-1);
                   9494:     }
                   9495:     my $output;
                   9496:     if (@lines) {
                   9497:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9498:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9499:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9500:         my %idmap = &username_to_idmap($classlist);
                   9501:         foreach my $key (keys(%idmap)) {
                   9502:             my $lckey = lc($key);
                   9503:             $idmap{$lckey} = $idmap{$key};
                   9504:         }
                   9505:         my %unique_formats;
1.596.2.12.2.  9(raebur 9506:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9507:         foreach my $line (@formatlines) {
                   9508:             chomp($line);
                   9509:             my @config = split(/:/,$line);
                   9510:             my $idstart = $config[5];
                   9511:             my $idlength = $config[6];
                   9512:             if (($idstart ne '') && ($idlength > 0)) {
                   9513:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9514:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9515:                 } else {
                   9516:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9517:                 }
                   9518:             }
                   9519:         }
                   9520:         foreach my $key (keys(%unique_formats)) {
                   9521:             my ($idstart,$idlength) = split(':',$key);
                   9522:             %{$counts{$key}} = (
                   9523:                                'found'   => 0,
                   9524:                                'total'   => 0,
                   9525:                               );
                   9526:             foreach my $line (@lines) {
                   9527:                 next if ($line =~ /^#/);
                   9528:                 next if ($line =~ /^[\s\cz]*$/);
                   9529:                 my $id = substr($line,$idstart-1,$idlength);
                   9530:                 $id = lc($id);
                   9531:                 if (exists($idmap{$id})) {
                   9532:                     $counts{$key}{'found'} ++;
                   9533:                 }
                   9534:                 $counts{$key}{'total'} ++;
                   9535:             }
                   9536:             if ($counts{$key}{'total'}) {
                   9537:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9538:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9539:                     $max_match_pct = $percent_match;
                   9540:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9541:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9542:                     $max_match_count = $counts{$key}{'total'};
                   9543:                 }
                   9544:             }
                   9545:         }
                   9546:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9547:             my $format_descs;
                   9548:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9549:             for (my $i=0; $i<$numwithformat; $i++) {
                   9550:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9551:                 if ($i<$numwithformat-2) {
                   9552:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9553:                 } elsif ($i==$numwithformat-2) {
                   9554:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9555:                 } elsif ($i==$numwithformat-1) {
                   9556:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9557:                 }
                   9558:             }
                   9559:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9560:3):             $output .= '<br />';
                   9561:3):             if ($found_match_count == $max_match_count) {
                   9562:3):                 # 100% matching entries
                   9563:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9564:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9565:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9566:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9567:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9568:3):                     ' in the file (for the format defined for [_3]).',
                   9569:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9570:3):             } else {
                   9571:3):                 # Not all entries matching? -> Show warning and additional info
                   9572:3):                 $output .=
                   9573:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9574:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9575:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9576:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9577:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9578:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9579:3):                         ' in the file (for the format defined for [_3]).',
                   9580:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9581:3):                     '<p class="LC_info">'.
                   9582:3):                     &mt('A low percentage of matches results from one of the following:').
                   9583:3):                     '</p><ul>'.
                   9584:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9585:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9586:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9587:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9588:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9589:3):                     '</ul>';
                   9590:3):             }
1.567     raeburn  9591:         }
                   9592:     } else {
1.596.2.12.2.  5(raebur 9593:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9594:     }
                   9595:     return $output;
                   9596: }
                   9597: 
1.202     albertel 9598: sub valid_file {
                   9599:     my ($requested_file)=@_;
                   9600:     foreach my $filename (sort(&scantron_filenames())) {
                   9601: 	if ($requested_file eq $filename) { return 1; }
                   9602:     }
                   9603:     return 0;
                   9604: }
                   9605: 
                   9606: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9607:0):     my ($r,$symb) = @_;
          (raeburn 9608:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9609:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9610:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9611:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9612:     if (! &valid_file($file)) {
1.492     albertel 9613: 	$r->print('
1.202     albertel 9614: 	<p>
1.596.2.12.2.  3(raebur 9615:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9616:         </p>
1.492     albertel 9617: ');
1.202     albertel 9618: 	return;
                   9619:     }
                   9620:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9621:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9622:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9623:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9624:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9625:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9626:     $r->print('
1.202     albertel 9627:     <p>
1.596.2.12.2.  1(raebur 9628:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9629: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9630:     </p>
                   9631:     <p>
1.492     albertel 9632: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9633: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9634:     </p>
                   9635:     <p>
1.492     albertel 9636: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9637: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9638:     </p>
1.492     albertel 9639: ');
1.202     albertel 9640:     return '';
                   9641: }
1.157     albertel 9642: 
1.523     raeburn  9643: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9644:0):     my ($r,$symb) = @_;
1.523     raeburn  9645:     if (!$symb) {return '';}
                   9646:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9647:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9648:     my $numletts = scalar(keys(%lettdig));
                   9649:     my $cnum = $env{'course.'.$cid.'.num'};
                   9650:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9651:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9652:     my %record;
                   9653:     my %scantron_config =
1.596.2.12.2.  9(raebur 9654:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9655:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9656:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9657:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9658:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9659:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9660:     unless (ref($navmap)) {
                   9661:         $r->print(&navmap_errormsg());
                   9662:         return '';
                   9663:     }
1.523     raeburn  9664:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9665:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9666:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9667:2):     if (ref($map)) {
                   9668:2):         $randomorder=$map->randomorder();
          7(raebur 9669:3):         $randompick=$map->randompick();
          0(raebur 9670:2):         unless ($randomorder || $randompick) {
                   9671:2):             foreach my $res ($navmap->retrieveResources($map,sub { $_[0]->is_map() },1,0,1)) {
                   9672:2):                 if ($res->randomorder()) {
                   9673:2):                     $randomorder = 1;
                   9674:2):                 }
                   9675:2):                 if ($res->randompick()) {
                   9676:2):                     $randompick = 1;
                   9677:2):                 }
                   9678:2):                 last if ($randomorder || $randompick);
                   9679:2):             }
                   9680:2):         }
          1(raebur 9681:2):     }
1.557     raeburn  9682:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9683:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9684:3):     if ($nav_error) {
                   9685:3):         $r->print(&navmap_errormsg());
                   9686:3):         return '';
          1(raebur 9687:2):     }
          (raeburn 9688:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9689:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9690:     my ($uname,$udom);
1.523     raeburn  9691:     my (%scandata,%lastname,%bylast);
                   9692:     $r->print('
                   9693: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9694: 
                   9695:     my @delayqueue;
                   9696:     my %completedstudents;
                   9697: 
1.596.2.12.2.  6(raebur 9698:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9699:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9700:3):     my ($username,$domain,$started);
          (raeburn 9701:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9702:     if ($nav_error) {
                   9703:         $r->print(&navmap_errormsg());
                   9704:         return '';
                   9705:     }
1.523     raeburn  9706: 
                   9707:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9708:                                           'Processing first student');
                   9709:     my $start=&Time::HiRes::time();
                   9710:     my $i=-1;
                   9711: 
                   9712:     while ($i<$scanlines->{'count'}) {
                   9713:         ($username,$domain,$uname)=('','','');
                   9714:         $i++;
                   9715:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9716:         if ($line=~/^[\s\cz]*$/) { next; }
                   9717:         if ($started) {
                   9718:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9719:                                                      'last student');
                   9720:         }
                   9721:         $started=1;
                   9722:         my $scan_record=
                   9723:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9724:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9725:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9726:3):                                               \%idmap,$i)) {
1.523     raeburn  9727:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9728:                                 'Unable to find a student that matches',1);
                   9729:             next;
                   9730:         }
                   9731:         if (exists $completedstudents{$uname}) {
                   9732:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9733:                                 'Student '.$uname.' has multiple sheets',2);
                   9734:             next;
                   9735:         }
                   9736:         my $pid = $scan_record->{'scantron.ID'};
                   9737:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9738:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9739:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9740:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9741:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9742:2): 
                   9743:2):         my $scancode;
                   9744:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9745:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9746:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9747:2):         } else {
                   9748:2):             $scancode = '';
                   9749:2):         }
                   9750:2): 
                   9751:2):         my @mapresources = @resources;
          6(raebur 9752:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9753:3):         my %respnumlookup=();
                   9754:3):         my %startline=();
                   9755:3):         if ($randomorder || $randompick) {
          1(raebur 9756:2):             @mapresources =
          6(raebur 9757:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9758:3):                              \%orderedforcode);
                   9759:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9760:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9761:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9762:3):                                              \%respnumlookup,\%startline);
                   9763:3):             if ($randompick && $total) {
                   9764:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9765:3):             }
          1(raebur 9766:2):         }
          6(raebur 9767:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9768:3):         chomp($scandata{$pid});
                   9769:3):         $scandata{$pid} =~ s/\r$//;
                   9770:3): 
1.523     raeburn  9771:         my $counter = -1;
1.596.2.12.2.  1(raebur 9772:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9773:             my $parts;
1.554     raeburn  9774:             my $ressymb = $resource->symb();
1.557     raeburn  9775:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9776:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9777:7):                 my $currcode;
                   9778:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9779:7):                     $currcode = $scancode;
                   9780:7):                 }
1.557     raeburn  9781:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9782:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9783:):                                               $username,$domain,undef,
          1(raebur 9784:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9785:             } else {
                   9786:                 $parts = $grader_partids_by_symb{$ressymb};
                   9787:             }
1.542     raeburn  9788:             ($counter,my $recording) =
                   9789:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9790:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9791:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9792:3):                                          $randomorder,$randompick,
                   9793:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9794:             $record{$pid} .= $recording;
1.523     raeburn  9795:         }
                   9796:     }
                   9797:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9798:     $r->print('<br />');
                   9799:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9800:     $passed = 0;
                   9801:     $failed = 0;
                   9802:     $numstudents = 0;
                   9803:     foreach my $last (sort(keys(%bylast))) {
                   9804:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9805:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9806:                 my $showscandata = $scandata{$pid};
                   9807:                 my $showrecord = $record{$pid};
                   9808:                 $showscandata =~ s/\s/&nbsp;/g;
                   9809:                 $showrecord =~ s/\s/&nbsp;/g;
                   9810:                 if ($scandata{$pid} eq $record{$pid}) {
                   9811:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9812:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9813: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9814: '</tr>'."\n".
                   9815: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9816:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9817:                     $passed ++;
                   9818:                 } else {
                   9819:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9820:                     $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  9821: '</tr>'."\n".
                   9822: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9823:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9824: '</tr>'."\n";
                   9825:                     $failed ++;
                   9826:                 }
                   9827:                 $numstudents ++;
                   9828:             }
                   9829:         }
                   9830:     }
1.596.2.4  raeburn  9831:     $r->print('<p>'.
1.596.2.8  raeburn  9832:               &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  9833:                   '<b>',
                   9834:                   $numstudents,
                   9835:                   '</b>',
                   9836:                   $env{'form.scantron_maxbubble'}).
                   9837:               '</p>'
                   9838:     );
1.596.2.12.2.  2(raebur 9839:2):     $r->print('<p>'
                   9840:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9841:2):              .'<br />'
                   9842:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9843:2):              .'</p>');
1.523     raeburn  9844:     if ($passed) {
1.572     www      9845:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9846:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9847:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9848:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9849:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9850:                  $okstudents."\n".
                   9851:                  &Apache::loncommon::end_data_table().'<br />');
                   9852:     }
                   9853:     if ($failed) {
1.572     www      9854:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9855:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9856:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9857:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9858:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9859:                  $badstudents."\n".
                   9860:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9861:                  &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  9862:     }
1.596.2.12.2.  1(raebur 9863:0):     $r->print('</form><br />');
1.523     raeburn  9864:     return;
                   9865: }
                   9866: 
1.542     raeburn  9867: sub verify_scantron_grading {
1.554     raeburn  9868:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9869:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9870:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9871:     my ($record,%expected,%startpos);
                   9872:     return ($counter,$record) if (!ref($resource));
                   9873:     return ($counter,$record) if (!$resource->is_problem());
                   9874:     my $symb = $resource->symb();
1.554     raeburn  9875:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9876:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9877:         $counter ++;
                   9878:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9879:3):         my $respnum = $counter;
                   9880:3):         if ($randomorder || $randompick) {
                   9881:3):             $respnum = $respnumlookup->{$counter};
                   9882:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9883:3):         } else {
                   9884:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9885:3):         }
                   9886:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9887:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9888:             foreach my $item (@sub_lines) {
                   9889:                 $expected{$part_id} += $item;
                   9890:             }
                   9891:         } else {
1.596.2.12.2.  6(raebur 9892:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9893:         }
                   9894:     }
                   9895:     if ($symb) {
                   9896:         my %recorded;
                   9897:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9898:         if ($returnhash{'version'}) {
                   9899:             my %lasthash=();
                   9900:             my $version;
                   9901:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9902:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9903:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9904:                 }
                   9905:             }
                   9906:             foreach my $key (keys(%lasthash)) {
                   9907:                 if ($key =~ /\.scantron$/) {
                   9908:                     my $value = &unescape($lasthash{$key});
                   9909:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9910:                     if ($value eq '') {
                   9911:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9912:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9913:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9914:                             }
                   9915:                         }
                   9916:                     } else {
                   9917:                         my @tocheck;
                   9918:                         my @items = split(//,$value);
                   9919:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9920:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9921:                             if (@items < $expected{$part_id}) {
                   9922:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9923:                                 my @singles = split(//,$fragment);
                   9924:                                 foreach my $pos (@singles) {
                   9925:                                     if ($pos eq ' ') {
                   9926:                                         push(@tocheck,$pos);
                   9927:                                     } else {
                   9928:                                         my $next = shift(@items);
                   9929:                                         push(@tocheck,$next);
                   9930:                                     }
                   9931:                                 }
                   9932:                             } else {
                   9933:                                 @tocheck = @items;
                   9934:                             }
                   9935:                             foreach my $letter (@tocheck) {
                   9936:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9937:                                     if ($letter !~ /^[A-J]$/) {
                   9938:                                         $letter = $scantron_config->{'Qoff'};
                   9939:                                     }
                   9940:                                     $recorded{$part_id} .= $letter;
                   9941:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9942:                                     my $digit;
                   9943:                                     if ($letter !~ /^[A-J]$/) {
                   9944:                                         $digit = $scantron_config->{'Qoff'};
                   9945:                                     } else {
                   9946:                                         $digit = $lettdig->{$letter};
                   9947:                                     }
                   9948:                                     $recorded{$part_id} .= $digit;
                   9949:                                 }
                   9950:                             }
                   9951:                         } else {
                   9952:                             @tocheck = @items;
                   9953:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9954:                                 my $curr_sub = shift(@tocheck);
                   9955:                                 my $digit;
                   9956:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9957:                                     $digit = $lettdig->{$curr_sub}-1;
                   9958:                                 }
                   9959:                                 if ($curr_sub eq 'J') {
                   9960:                                     $digit += scalar($numletts);
                   9961:                                 }
                   9962:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9963:                                     if ($j == $digit) {
                   9964:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9965:                                     } else {
                   9966:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9967:                                     }
                   9968:                                 }
                   9969:                             }
                   9970:                         }
                   9971:                     }
                   9972:                 }
                   9973:             }
                   9974:         }
1.554     raeburn  9975:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9976:             if ($recorded{$part_id} eq '') {
                   9977:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9978:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9979:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9980:                     }
                   9981:                 }
                   9982:             }
                   9983:             $record .= $recorded{$part_id};
                   9984:         }
                   9985:     }
                   9986:     return ($counter,$record);
                   9987: }
                   9988: 
1.75      albertel 9989: #-------- end of section for handling grading scantron forms -------
                   9990: #
                   9991: #-------------------------------------------------------------------
                   9992: 
1.72      ng       9993: #-------------------------- Menu interface -------------------------
                   9994: #
1.596.2.12.2.  (raeburn 9995:): #--- Href with symb and command ---
                   9996:): 
                   9997:): sub href_symb_cmd {
                   9998:):     my ($symb,$cmd)=@_;
                   9999:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   10000:): }
                   10001:): 
1.443     banghart 10002: sub grading_menu {
1.596.2.12.2.  1(raebur 10003:0):     my ($request,$symb) = @_;
1.443     banghart 10004:     if (!$symb) {return '';}
                   10005: 
                   10006:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 10007:0):                   'command'=>'individual');
                   10008:0): 
                   10009:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10010:0): 
                   10011:0):     $fields{'command'}='ungraded';
                   10012:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10013:0): 
                   10014:0):     $fields{'command'}='table';
                   10015:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10016:0): 
                   10017:0):     $fields{'command'}='all_for_one';
                   10018:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10019:0): 
                   10020:0):     $fields{'command'}='downloadfilesselect';
                   10021:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10022:     
1.443     banghart 10023:     $fields{'command'} = 'csvform';
1.538     schulted 10024:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10025:     
1.443     banghart 10026:     $fields{'command'} = 'processclicker';
1.538     schulted 10027:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10028:     
1.443     banghart 10029:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10030:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 10031:0): 
                   10032:0):     $fields{'command'} = 'initialverifyreceipt';
                   10033:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
          6(raebur 10034:1): 
                   10035:1):     my %permissions;
                   10036:1):     if ($perm{'mgr'}) {
                   10037:1):         $permissions{'either'} = 'F';
                   10038:1):         $permissions{'mgr'} = 'F';
                   10039:1):     }
                   10040:1):     if ($perm{'vgr'}) {
                   10041:1):         $permissions{'either'} = 'F';
                   10042:1):         $permissions{'vgr'} = 'F';
                   10043:1):     }
                   10044:1): 
          1(raebur 10045:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10046:             items =>[
1.596.2.12.2.  1(raebur 10047:0):                         {       linktext => 'Select individual students to grade',
                   10048:0):                                 url => $url1a,
          6(raebur 10049:1):                                 permission => $permissions{'either'},
          1(raebur 10050:0):                                 icon => 'grade_students.png',
                   10051:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   10052:0):                         },
                   10053:0):                         {       linktext => 'Grade ungraded submissions',
                   10054:0):                                 url => $url1b,
          6(raebur 10055:1):                                 permission => $permissions{'either'},
          1(raebur 10056:0):                                 icon => 'ungrade_sub.png',
                   10057:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   10058:0):                         },
                   10059:0): 
                   10060:0):                         {       linktext => 'Grading table',
                   10061:0):                                 url => $url1c,
          6(raebur 10062:1):                                 permission => $permissions{'either'},
          1(raebur 10063:0):                                 icon => 'grading_table.png',
                   10064:0):                                 linktitle => 'Grade current resource for all students.'
                   10065:0):                         },
                   10066:0):                         {       linktext => 'Grade page/folder for one student',
                   10067:0):                                 url => $url1d,
          6(raebur 10068:1):                                 permission => $permissions{'either'},
          1(raebur 10069:0):                                 icon => 'grade_PageFolder.png',
                   10070:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 10071:                         },
1.596.2.12.2.  3(raebur 10072:0):                         {       linktext => 'Download submitted files',
          1(raebur 10073:0):                                 url => $url1e,
          6(raebur 10074:1):                                 permission => $permissions{'either'},
          1(raebur 10075:0):                                 icon => 'download_sub.png',
          3(raebur 10076:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 10077:0):                         }]},
                   10078:0):                          { categorytitle=>'Automated Grading',
                   10079:0):                items =>[
                   10080:0): 
1.538     schulted 10081:                 	    {	linktext => 'Upload Scores',
                   10082:                     		url => $url2,
1.596.2.12.2.  6(raebur 10083:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10084:                     		icon => 'uploadscores.png',
                   10085:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10086:                 	    },
                   10087:                 	    {	linktext => 'Process Clicker',
                   10088:                     		url => $url3,
1.596.2.12.2.  6(raebur 10089:1):                     		permission => $permissions{'mgr'},
1.538     schulted 10090:                     		icon => 'addClickerInfoFile.png',
                   10091:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10092:                 	    },
1.587     raeburn  10093:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10094:                     		url => $url4,
1.596.2.12.2.  6(raebur 10095:1):                     		permission => $permissions{'mgr'},
          1(raebur 10096:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  10097:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 10098:0):                 	    },
                   10099:0):                             {   linktext => 'Verify Receipt Number',
                   10100:0):                                 url => $url5,
          6(raebur 10101:1):                                 permission => $permissions{'either'},
          1(raebur 10102:0):                                 icon => 'receipt_number.png',
                   10103:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10104:0):                             }
                   10105:0): 
1.538     schulted 10106:                     ]
                   10107:             });
                   10108: 
1.443     banghart 10109:     # Create the menu
                   10110:     my $Str;
1.445     banghart 10111:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10112:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 10113:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 10114: 
1.596.2.12.2.  1(raebur 10115:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10116:     return $Str;    
                   10117: }
                   10118: 
1.596.2.12.2.  1(raebur 10119:0): sub ungraded {
                   10120:0):     my ($request)=@_;
                   10121:0):     &submit_options($request);
                   10122:0): }
1.443     banghart 10123: 
1.596.2.12.2.  1(raebur 10124:0): sub submit_options_sequence {
                   10125:0):     my ($request,$symb) = @_;
1.72      ng       10126:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 10127:0):     &commonJSfunctions($request);
                   10128:0):     my $result;
1.72      ng       10129: 
1.596.2.12.2.  1(raebur 10130:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10131:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10132:0):     $result.=&selectfield(0).
                   10133:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   10134:0):             <div>
                   10135:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10136:0):             </div>
                   10137:0):         </div>
                   10138:0):   </form>';
                   10139:0):     return $result;
                   10140:0): }
                   10141:0): 
                   10142:0): sub submit_options_table {
                   10143:0):     my ($request,$symb) = @_;
                   10144:0):     if (!$symb) {return '';}
1.118     ng       10145:     &commonJSfunctions($request);
1.473     albertel 10146:     my $result;
1.596.2.12.2.  1(raebur 10147:0): 
                   10148:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10149:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10150:0): 
                   10151:0):     $result.=&selectfield(1).
                   10152:0):             '<input type="hidden" name="command" value="viewgrades" />
                   10153:0):             <div>
                   10154:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10155:0):             </div>
                   10156:0):         </div>
                   10157:0):   </form>';
                   10158:0):     return $result;
                   10159:0): }
                   10160:0): 
                   10161:0): sub submit_options_download {
                   10162:0):     my ($request,$symb) = @_;
                   10163:0):     if (!$symb) {return '';}
                   10164:0): 
                   10165:0):     my $res_error;
                   10166:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   10167:0):         &response_type($symb,\$res_error);
                   10168:0):     if ($res_error) {
                   10169:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10170:0):         return;
                   10171:0):     }
                   10172:0):     unless ($numessay) {
                   10173:0):         $request->print(&mt('No essayresponse items found'));
                   10174:0):         return;
                   10175:0):     }
                   10176:0):     my $table;
                   10177:0):     if (ref($partlist) eq 'ARRAY') {
                   10178:0):         if (scalar(@$partlist) > 1 ) {
                   10179:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10180:         }
                   10181:     }
                   10182: 
1.596.2.12.2.  1(raebur 10183:0):     &commonJSfunctions($request);
1.72      ng       10184: 
1.596.2.12.2.  1(raebur 10185:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10186:0):         $table."\n".
                   10187:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10188:     $result.='
1.533     bisitz   10189: <h2>
1.596.2.12.2.  3(raebur 10190:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          1(raebur 10191:0): </h2>'.&selectfield(1).'
                   10192:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10193:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10194:0):             </div>
                   10195:0):           </div>
                   10196:0): 
                   10197:0): 
                   10198:0):   </form>';
                   10199:0):     return $result;
                   10200:0): }
                   10201:0): 
                   10202:0): #--- Displays the submissions first page -------
                   10203:0): sub submit_options {
                   10204:0):     my ($request,$symb) = @_;
                   10205:0):     if (!$symb) {return '';}
                   10206:0): 
                   10207:0):     &commonJSfunctions($request);
                   10208:0):     my $result;
                   10209:0): 
                   10210:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10211:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10212:0):     $result.=&selectfield(1).'
                   10213:0):                 <input type="hidden" name="command" value="submission" />
                   10214:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10215:0):             </div>
                   10216:0):           </div>
                   10217:0):   </form>';
                   10218:0):     return $result;
                   10219:0): }
                   10220:0): 
                   10221:0): sub selectfield {
                   10222:0):    my ($full)=@_;
                   10223:0):    my %options =
                   10224:0):        (&substatus_options,
                   10225:0):         'select_form_order' => ['yes','queued','graded','incorrect','all']);
          7(raebur 10226:1): 
                   10227:1):   #
                   10228:1):   # PrepareClasslist() needs to be called to avoid getting a sections list
                   10229:1):   # for a different course from the @Sections global in lonstatistics.pm,
                   10230:1):   # populated by an earlier request.
                   10231:1):   #
                   10232:1):    &Apache::lonstatistics::PrepareClasslist();
                   10233:1): 
          1(raebur 10234:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10235: 
                   10236:     <fieldset>
                   10237:       <legend>
                   10238:        '.&mt('Sections').'
                   10239:       </legend>
1.596.2.12.2.  1(raebur 10240:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10241:     </fieldset>
1.596.2.12.2.  1(raebur 10242:0): 
1.533     bisitz   10243:     <fieldset>
                   10244:       <legend>
                   10245:         '.&mt('Groups').'
                   10246:       </legend>
                   10247:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10248:     </fieldset>
1.596.2.12.2.  1(raebur 10249:0):  
1.533     bisitz   10250:     <fieldset>
                   10251:       <legend>
                   10252:         '.&mt('Access Status').'
                   10253:       </legend>
1.596.2.12.2.  1(raebur 10254:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10255:0):     </fieldset>';
                   10256:0):     if ($full) {
                   10257:0):         $result.='
1.533     bisitz   10258:     <fieldset>
                   10259:       <legend>
                   10260:         '.&mt('Submission Status').'
1.596.2.12.2.  1(raebur 10261:0):       </legend>'.
                   10262:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10263:0):    '</fieldset>';
                   10264:0):     }
                   10265:0):     $result.='</div><br />';
1.44      ng       10266:     return $result;
1.2       albertel 10267: }
                   10268: 
1.596.2.12.2.  7(raebur 10269:6): sub substatus_options {
                   10270:6):     return &Apache::lonlocal::texthash(
                   10271:6):                                       'yes'       => 'with submissions',
                   10272:6):                                       'queued'    => 'in grading queue',
                   10273:6):                                       'graded'    => 'with ungraded submissions',
                   10274:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10275:7):                                       'all'       => 'with any status',
                   10276:7):                                       );
          7(raebur 10277:6): }
                   10278:6): 
          1(raebur 10279:0): sub transtatus_options {
                   10280:0):     return &Apache::lonlocal::texthash(
                   10281:0):                                        'yes'       => 'with score transactions',
                   10282:0):                                        'incorrect' => 'with less than full credit',
                   10283:0):                                        'all'       => 'with any status',
                   10284:0):                                       );
                   10285:0): }
                   10286:0): 
1.285     albertel 10287: sub reset_perm {
                   10288:     undef(%perm);
                   10289: }
                   10290: 
                   10291: sub init_perm {
                   10292:     &reset_perm();
1.300     albertel 10293:     foreach my $test_perm ('vgr','mgr','opa') {
                   10294: 
                   10295: 	my $scope = $env{'request.course.id'};
                   10296: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10297: 
                   10298: 	    $scope .= '/'.$env{'request.course.sec'};
                   10299: 	    if ( $perm{$test_perm}=
                   10300: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10301: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10302: 	    } else {
                   10303: 		delete($perm{$test_perm});
                   10304: 	    }
1.285     albertel 10305: 	}
                   10306:     }
                   10307: }
                   10308: 
1.596.2.12.2.  (raeburn 10309:): sub init_old_essays {
                   10310:):     my ($symb,$apath,$adom,$aname) = @_;
                   10311:):     if ($symb ne '') {
                   10312:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10313:):         if (keys(%essays) > 0) {
                   10314:):             $old_essays{$symb} = \%essays;
                   10315:):         }
                   10316:):     }
                   10317:):     return;
                   10318:): }
                   10319:): 
                   10320:): sub reset_old_essays {
                   10321:):     undef(%old_essays);
                   10322:): }
                   10323:): 
1.400     www      10324: sub gather_clicker_ids {
1.408     albertel 10325:     my %clicker_ids;
1.400     www      10326: 
                   10327:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10328: 
                   10329:     # Set up a couple variables.
1.407     albertel 10330:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10331:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10332:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10333: 
1.407     albertel 10334:     foreach my $student (keys(%$classlist)) {
1.438     www      10335:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10336:         my $username = $classlist->{$student}->[$username_idx];
                   10337:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10338:         my $clickers =
1.408     albertel 10339: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10340:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10341:             $id=~s/^[\#0]+//;
1.421     www      10342:             $id=~s/[\-\:]//g;
1.407     albertel 10343:             if (exists($clicker_ids{$id})) {
1.408     albertel 10344: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10345:             } else {
1.408     albertel 10346: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10347:             }
                   10348:         }
                   10349:     }
1.407     albertel 10350:     return %clicker_ids;
1.400     www      10351: }
                   10352: 
1.402     www      10353: sub gather_adv_clicker_ids {
1.408     albertel 10354:     my %clicker_ids;
1.402     www      10355:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10356:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10357:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10358:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10359:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10360:             my ($puname,$pudom)=split(/\:/,$person);
                   10361:             my $clickers =
1.408     albertel 10362: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10363:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10364: 		$id=~s/^[\#0]+//;
1.421     www      10365:                 $id=~s/[\-\:]//g;
1.408     albertel 10366: 		if (exists($clicker_ids{$id})) {
                   10367: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10368: 		} else {
                   10369: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10370: 		}
1.405     www      10371:             }
1.402     www      10372:         }
                   10373:     }
1.407     albertel 10374:     return %clicker_ids;
1.402     www      10375: }
                   10376: 
1.413     www      10377: sub clicker_grading_parameters {
                   10378:     return ('gradingmechanism' => 'scalar',
                   10379:             'upfiletype' => 'scalar',
                   10380:             'specificid' => 'scalar',
                   10381:             'pcorrect' => 'scalar',
                   10382:             'pincorrect' => 'scalar');
                   10383: }
                   10384: 
1.400     www      10385: sub process_clicker {
1.596.2.12.2.  1(raebur 10386:0):     my ($r,$symb)=@_;
1.400     www      10387:     if (!$symb) {return '';}
                   10388:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10389:0):     $result.=&Apache::loncommon::start_data_table().
                   10390:0):              &Apache::loncommon::start_data_table_header_row().
                   10391:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10392:0):              &Apache::loncommon::end_data_table_header_row().
                   10393:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10394: # Attempt to restore parameters from last session, set defaults if not present
                   10395:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10396:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10397:                                                  \%Saveable_Parameters);
                   10398:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10399:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10400:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10401:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10402: 
                   10403:     my %checked;
1.521     www      10404:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10405:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10406:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10407:        }
                   10408:     }
                   10409: 
1.596.2.12.2.  1(raebur 10410:0):     my $upload=&mt("Evaluate File");
1.400     www      10411:     my $type=&mt("Type");
1.402     www      10412:     my $attendance=&mt("Award points just for participation");
                   10413:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10414:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10415:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10416:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10417:     my $pcorrect=&mt("Percentage points for correct solution");
                   10418:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10419:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10420:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10421:):                                                     'interwrite' => 'interwrite PRS',
                   10422:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10423:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10424:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10425: function sanitycheck() {
                   10426: // Accept only integer percentages
                   10427:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10428:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10429: // Find out grading choice
                   10430:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10431:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10432:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10433:       }
                   10434:    }
                   10435: // By default, new choice equals user selection
                   10436:    newgradingchoice=gradingchoice;
                   10437: // Not good to give more points for false answers than correct ones
                   10438:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10439:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10440:    }
                   10441: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10442:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10443:       document.forms.gradesupload.pcorrect.value=100;
                   10444:       document.forms.gradesupload.pincorrect.value=100;
                   10445:    }
                   10446: // If the values are different, cannot be attendance only
                   10447:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10448:        (gradingchoice=='attendance')) {
                   10449:        newgradingchoice='personnel';
                   10450:    }
                   10451: // Change grading choice to new one
                   10452:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10453:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10454:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10455:       } else {
                   10456:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10457:       }
                   10458:    }
                   10459: // Remember the old state
                   10460:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10461: }
1.596.2.12.2.  1(raebur 10462:0): ENDUPFORM
                   10463:0):     $result.= <<ENDUPFORM;
1.400     www      10464: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10465: <input type="hidden" name="symb" value="$symb" />
                   10466: <input type="hidden" name="command" value="processclickerfile" />
                   10467: <input type="file" name="upfile" size="50" />
                   10468: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10469:0): ENDUPFORM
                   10470:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10471:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10472:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10473: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10474: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10475: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10476: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10477: <br />&nbsp;&nbsp;&nbsp;
                   10478: <input type="text" name="givenanswer" size="50" />
1.413     www      10479: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10480:0): ENDGRADINGFORM
                   10481:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10482:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10483:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10484: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10485: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10486: </form>
1.596.2.12.2.  1(raebur 10487:0): ENDPERCFORM
                   10488:0):     $result.='</td>'.
                   10489:0):              &Apache::loncommon::end_data_table_row().
                   10490:0):              &Apache::loncommon::end_data_table();
1.400     www      10491:     return $result;
                   10492: }
                   10493: 
                   10494: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10495:0):     my ($r,$symb) = @_;
1.400     www      10496:     if (!$symb) {return '';}
1.413     www      10497: 
                   10498:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10499:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10500:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10501:0):     my $result='';
1.404     www      10502:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10503: 	$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 10504:0): 	return $result;
1.404     www      10505:     }
1.522     www      10506:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10507:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10508:0):         return $result;
1.521     www      10509:     }
1.522     www      10510:     my $foundgiven=0;
1.521     www      10511:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10512:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10513:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10514:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10515:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10516:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10517:         $foundgiven=$#answers+1;
1.521     www      10518:     }
1.407     albertel 10519:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10520:     my %correct_ids;
1.404     www      10521:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10522: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10523:     }
                   10524:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10525: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10526: 	   $correct_id=~tr/a-z/A-Z/;
                   10527: 	   $correct_id=~s/\s//gs;
                   10528: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10529:            $correct_id=~s/[\-\:]//g;
1.414     www      10530:            if ($correct_id) {
                   10531: 	      $correct_ids{$correct_id}='specified';
                   10532:            }
                   10533:         }
1.400     www      10534:     }
1.404     www      10535:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10536: 	$result.=&mt('Score based on attendance only');
1.521     www      10537:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10538:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10539:     } else {
1.408     albertel 10540: 	my $number=0;
1.411     www      10541: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10542: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10543: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10544: 	    if ($correct_ids{$id} eq 'specified') {
                   10545: 		$result.=&mt('specified');
                   10546: 	    } else {
                   10547: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10548: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10549: 	    }
                   10550: 	    $number++;
                   10551: 	}
1.411     www      10552:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10553:3):         if ($number==0) {
                   10554:3):             $result .=
                   10555:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10556:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10557:0):             return $result;
          5(raebur 10558:3):         }
1.404     www      10559:     }
1.405     www      10560:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10561:3):         $result .=
                   10562:3):             &Apache::lonhtmlcommon::confirm_success(
                   10563:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10564:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10565:0):         return $result;
1.405     www      10566:     }
1.596.2.12.2.  7(raebur 10567:9):     my $mimetype;
                   10568:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10569:9):         my $mm = new File::MMagic;
                   10570:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10571:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10572:9):             $result.= '<p>'.
                   10573:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10574:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10575:0):             return $result;
          7(raebur 10576:9):         }
                   10577:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10578:9):         $result .= '<p>'.
                   10579:9):             &Apache::lonhtmlcommon::confirm_success(
                   10580:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10581:0):         return $result;
          7(raebur 10582:9):     }
1.410     www      10583: 
                   10584: # Were able to get all the info needed, now analyze the file
                   10585: 
1.411     www      10586:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10587:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10588:0):     $result.=&Apache::loncommon::start_data_table().
                   10589:0):              &Apache::loncommon::start_data_table_header_row().
                   10590:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10591:0):              &Apache::loncommon::end_data_table_header_row().
                   10592:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10593:0): <td>
1.410     www      10594: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10595: <input type="hidden" name="symb" value="$symb" />
                   10596: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10597: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10598: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10599: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10600: ENDHEADER
1.522     www      10601:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10602:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10603:     } 
1.408     albertel 10604:     my %responses;
                   10605:     my @questiontitles;
1.405     www      10606:     my $errormsg='';
                   10607:     my $number=0;
                   10608:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10609:9):         if ($mimetype eq 'text/plain') {
                   10610:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10611:9):         } elsif ($mimetype eq 'text/html') {
                   10612:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10613:9):         }
                   10614:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10615:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10616:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10617:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10618:):     }
1.411     www      10619:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10620:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10621:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10622:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10623:              '<br />';
1.522     www      10624:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10625:        $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 10626:0):        return $result;
1.522     www      10627:     } 
1.414     www      10628: # Remember Question Titles
                   10629: # FIXME: Possibly need delimiter other than ":"
                   10630:     for (my $i=0;$i<$number;$i++) {
                   10631:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10632:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10633:     }
1.411     www      10634:     my $correct_count=0;
                   10635:     my $student_count=0;
                   10636:     my $unknown_count=0;
1.414     www      10637: # Match answers with usernames
                   10638: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10639:     foreach my $id (keys(%responses)) {
1.410     www      10640:        if ($correct_ids{$id}) {
1.414     www      10641:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10642:           $correct_count++;
1.410     www      10643:        } elsif ($clicker_ids{$id}) {
1.437     www      10644:           if ($clicker_ids{$id}=~/\,/) {
                   10645: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10646:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10647:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10648:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10649:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10650:                            "<select name='multi".$id."'>";
                   10651:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10652:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10653:              }
                   10654:              $result.='</select>';
                   10655:              $unknown_count++;
                   10656:           } else {
                   10657: # Good: found one and only one user with the right clicker
                   10658:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10659:              $student_count++;
                   10660:           }
1.410     www      10661:        } else {
1.596.2.12.2.  1(raebur 10662:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10663:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10664:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10665:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10666:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10667:                    "\n".&mt("Domain").": ".
                   10668:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10669:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10670:           $unknown_count++;
1.410     www      10671:        }
1.405     www      10672:     }
1.412     www      10673:     $result.='<hr />'.
                   10674:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10675:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10676:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10677:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10678:        } elsif ($correct_count>1) {
1.414     www      10679:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10680:        }
                   10681:     }
1.428     www      10682:     if ($number<1) {
                   10683:        $errormsg.="Found no questions.";
                   10684:     }
1.412     www      10685:     if ($errormsg) {
                   10686:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10687:     } else {
                   10688:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10689:     }
1.596.2.12.2.  1(raebur 10690:0):     $result.='</form></td>'.
                   10691:0):              &Apache::loncommon::end_data_table_row().
                   10692:0):              &Apache::loncommon::end_data_table();
                   10693:0):     return $result;
1.400     www      10694: }
                   10695: 
1.405     www      10696: sub iclicker_eval {
1.406     www      10697:     my ($questiontitles,$responses)=@_;
1.405     www      10698:     my $number=0;
                   10699:     my $errormsg='';
                   10700:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10701:         my %components=&Apache::loncommon::record_sep($line);
                   10702:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10703: 	if ($entries[0] eq 'Question') {
                   10704: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10705: 		$$questiontitles[$number]=$entries[$i];
                   10706: 		$number++;
                   10707: 	    }
                   10708: 	}
                   10709: 	if ($entries[0]=~/^\#/) {
                   10710: 	    my $id=$entries[0];
                   10711: 	    my @idresponses;
                   10712: 	    $id=~s/^[\#0]+//;
                   10713: 	    for (my $i=0;$i<$number;$i++) {
                   10714: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10715:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10716: 		push(@idresponses,$entries[$idx]);
                   10717: 	    }
                   10718: 	    $$responses{$id}=join(',',@idresponses);
                   10719: 	}
1.405     www      10720:     }
                   10721:     return ($errormsg,$number);
                   10722: }
                   10723: 
1.596.2.12.2.  7(raebur 10724:9): sub iclickerxml_eval {
                   10725:9):     my ($questiontitles,$responses)=@_;
                   10726:9):     my $number=0;
                   10727:9):     my $errormsg='';
                   10728:9):     my @state;
                   10729:9):     my %respbyid;
                   10730:9):     my $p = HTML::Parser->new
                   10731:9):     (
                   10732:9):         xml_mode => 1,
                   10733:9):         start_h =>
                   10734:9):             [sub {
                   10735:9):                  my ($tagname,$attr) = @_;
                   10736:9):                  push(@state,$tagname);
                   10737:9):                  if ("@state" eq "ssn p") {
                   10738:9):                      my $title = $attr->{qn};
                   10739:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10740:9):                      $questiontitles->[$number]=$title;
                   10741:9):                  } elsif ("@state" eq "ssn p v") {
                   10742:9):                      my $id = $attr->{id};
                   10743:9):                      my $entry = $attr->{ans};
                   10744:9):                      $id=~s/^[\#0]+//;
                   10745:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10746:9):                      $respbyid{$id}[$number] = $entry;
                   10747:9):                  }
                   10748:9):             }, "tagname, attr"],
                   10749:9):          end_h =>
                   10750:9):                [sub {
                   10751:9):                    my ($tagname) = @_;
                   10752:9):                    if ("@state" eq "ssn p") {
                   10753:9):                        $number++;
                   10754:9):                    }
                   10755:9):                    pop(@state);
                   10756:9):                 }, "tagname"],
                   10757:9):     );
                   10758:9): 
                   10759:9):     $p->parse($env{'form.upfile'});
                   10760:9):     $p->eof;
                   10761:9):     foreach my $id (keys(%respbyid)) {
                   10762:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10763:9):     }
                   10764:9):     return ($errormsg,$number);
                   10765:9): }
                   10766:9): 
1.419     www      10767: sub interwrite_eval {
                   10768:     my ($questiontitles,$responses)=@_;
                   10769:     my $number=0;
                   10770:     my $errormsg='';
1.420     www      10771:     my $skipline=1;
                   10772:     my $questionnumber=0;
                   10773:     my %idresponses=();
1.419     www      10774:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10775:         my %components=&Apache::loncommon::record_sep($line);
                   10776:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10777:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10778:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10779:         next if $skipline;
                   10780:         if ($entries[0]!=$questionnumber) {
                   10781:            $questionnumber=$entries[0];
                   10782:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10783:            $number++;
1.419     www      10784:         }
1.420     www      10785:         my $id=$entries[4];
                   10786:         $id=~s/^[\#0]+//;
1.421     www      10787:         $id=~s/^v\d*\://i;
                   10788:         $id=~s/[\-\:]//g;
1.420     www      10789:         $idresponses{$id}[$number]=$entries[6];
                   10790:     }
1.524     raeburn  10791:     foreach my $id (keys(%idresponses)) {
1.420     www      10792:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10793:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10794:     }
                   10795:     return ($errormsg,$number);
                   10796: }
                   10797: 
1.596.2.12.2.  (raeburn 10798:): sub turning_eval {
                   10799:):     my ($questiontitles,$responses)=@_;
                   10800:):     my $number=0;
                   10801:):     my $errormsg='';
                   10802:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10803:):         my %components=&Apache::loncommon::record_sep($line);
                   10804:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10805:):         if ($#entries>$number) { $number=$#entries; }
                   10806:):         my $id=$entries[0];
                   10807:):         my @idresponses;
                   10808:):         $id=~s/^[\#0]+//;
                   10809:):         unless ($id) { next; }
                   10810:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10811:):             $entries[$idx]=~s/\,/\;/g;
                   10812:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10813:):             push(@idresponses,$entries[$idx]);
                   10814:):         }
                   10815:):         $$responses{$id}=join(',',@idresponses);
                   10816:):     }
                   10817:):     for (my $i=1; $i<=$number; $i++) {
                   10818:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10819:):     }
                   10820:):     return ($errormsg,$number);
                   10821:): }
                   10822:): 
1.414     www      10823: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10824:0):     my ($r,$symb) = @_;
1.414     www      10825:     if (!$symb) {return '';}
1.416     www      10826: # See which part we are saving to
1.582     raeburn  10827:     my $res_error;
                   10828:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10829:     if ($res_error) {
                   10830:         return &navmap_errormsg();
                   10831:     }
1.416     www      10832: # FIXME: This should probably look for the first handgradeable part
                   10833:     my $part=$$partlist[0];
                   10834: # Start screen output
1.596.2.12.2.  1(raebur 10835:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10836:0):                  &Apache::loncommon::start_data_table_header_row().
                   10837:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10838:0):                  &Apache::loncommon::end_data_table_header_row().
                   10839:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10840: # Get correct result
                   10841: # FIXME: Possibly need delimiter other than ":"
                   10842:     my @correct=();
1.415     www      10843:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10844:     my $number=$env{'form.number'};
                   10845:     if ($gradingmechanism ne 'attendance') {
1.414     www      10846:        foreach my $key (keys(%env)) {
                   10847:           if ($key=~/^form\.correct\:/) {
                   10848:              my @input=split(/\,/,$env{$key});
                   10849:              for (my $i=0;$i<=$#input;$i++) {
                   10850:                  if (($correct[$i]) && ($input[$i]) &&
                   10851:                      ($correct[$i] ne $input[$i])) {
                   10852:                     $result.='<br /><span class="LC_warning">'.
                   10853:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10854:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10855:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10856:                     $correct[$i]=$input[$i];
                   10857:                  }
                   10858:              }
                   10859:           }
                   10860:        }
1.415     www      10861:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10862:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10863:              $result.='<br /><span class="LC_error">'.
                   10864:                       &mt('No correct result given for question "[_1]"!',
                   10865:                           $env{'form.question:'.$i}).'</span>';
                   10866:           }
                   10867:        }
1.596.2.4  raeburn  10868:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10869:     }
                   10870: # Start grading
1.415     www      10871:     my $pcorrect=$env{'form.pcorrect'};
                   10872:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10873:     my $storecount=0;
1.596.2.4  raeburn  10874:     my %users=();
1.415     www      10875:     foreach my $key (keys(%env)) {
1.420     www      10876:        my $user='';
1.415     www      10877:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10878:           $user=$1;
                   10879:        }
                   10880:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10881:           my $id=$1;
                   10882:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10883:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10884:           } elsif ($env{'form.multi'.$id}) {
                   10885:              $user=$env{'form.multi'.$id};
1.420     www      10886:           }
                   10887:        }
1.596.2.4  raeburn  10888:        if ($user) {
                   10889:           if ($users{$user}) {
                   10890:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10891:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10892:                       '</span><br />';
                   10893:           }
                   10894:           $users{$user}=1;
1.415     www      10895:           my @answer=split(/\,/,$env{$key});
                   10896:           my $sum=0;
1.522     www      10897:           my $realnumber=$number;
1.415     www      10898:           for (my $i=0;$i<$number;$i++) {
1.576     www      10899:              if  ($correct[$i] eq '-') {
                   10900:                 $realnumber--;
1.596.2.12.2.  1(raebur 10901:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      10902:                 if ($gradingmechanism eq 'attendance') {
                   10903:                    $sum+=$pcorrect;
1.576     www      10904:                 } elsif ($correct[$i] eq '*') {
1.522     www      10905:                    $sum+=$pcorrect;
1.415     www      10906:                 } else {
1.596.2.4  raeburn  10907: # We actually grade if correct or not
                   10908:                    my $increment=$pincorrect;
                   10909: # Special case: numerical answer "0"
                   10910:                    if ($correct[$i] eq '0') {
                   10911:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10912:                          $increment=$pcorrect;
                   10913:                       }
                   10914: # General numerical answer, both evaluate to something non-zero
                   10915:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10916:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10917:                          $increment=$pcorrect;
                   10918:                       }
                   10919: # Must be just alphanumeric
                   10920:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10921:                       $increment=$pcorrect;
1.415     www      10922:                    }
1.596.2.4  raeburn  10923:                    $sum+=$increment;
1.415     www      10924:                 }
                   10925:              }
                   10926:           }
1.522     www      10927:           my $ave=$sum/(100*$realnumber);
1.416     www      10928: # Store
                   10929:           my ($username,$domain)=split(/\:/,$user);
                   10930:           my %grades=();
                   10931:           $grades{"resource.$part.solved"}='correct_by_override';
                   10932:           $grades{"resource.$part.awarded"}=$ave;
                   10933:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10934:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10935:                                                  $env{'request.course.id'},
                   10936:                                                  $domain,$username);
                   10937:           if ($returncode ne 'ok') {
                   10938:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10939:           } else {
                   10940:              $storecount++;
                   10941:           }
1.415     www      10942:        }
                   10943:     }
                   10944: # We are done
1.549     hauer    10945:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10946:              '</td>'.
                   10947:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 10948:0):              &Apache::loncommon::end_data_table();
                   10949:0):     return $result;
1.414     www      10950: }
                   10951: 
1.582     raeburn  10952: sub navmap_errormsg {
                   10953:     return '<div class="LC_error">'.
                   10954:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10955:            &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  10956:            '</div>';
                   10957: }
                   10958: 
1.596.2.12.2.  (raeburn 10959:): sub startpage {
          5(raebur 10960:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$head_extra,$onload,$divforres) = @_;
          9(raebur 10961:9):     my %args;
                   10962:9):     if ($onload) {
                   10963:9):          my %loaditems = (
                   10964:9):                         'onload' => $onload,
                   10965:9):                       );
                   10966:9):          $args{'add_entries'} = \%loaditems;
                   10967:9):     }
          (raeburn 10968:):     if ($nomenu) {
          9(raebur 10969:9):         $args{'only_body'} = 1;
          5(raebur 10970:0):         $r->print(&Apache::loncommon::start_page("Student's Version",$head_extra,\%args));
          (raeburn 10971:):     } else {
          8(raebur 10972:1):         if ($env{'request.course.id'}) {
                   10973:1):             unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10974:1):         }
          9(raebur 10975:9):         $args{'bread_crumbs'} = $crumbs;
          5(raebur 10976:0):         $r->print(&Apache::loncommon::start_page('Grading',$head_extra,\%args));
          (raeburn 10977:):     }
                   10978:):     unless ($nodisplayflag) {
          1(raebur 10979:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 10980:):     }
                   10981:): }
                   10982:): 
          1(raebur 10983:0): sub select_problem {
                   10984:0):     my ($r)=@_;
                   10985:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   10986:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   10987:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10988:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10989:0): }
                   10990:0): 
1.1       albertel 10991: sub handler {
1.41      ng       10992:     my $request=$_[0];
1.434     albertel 10993:     &reset_caches();
1.596.2.4  raeburn  10994:     if ($request->header_only) {
                   10995:         &Apache::loncommon::content_type($request,'text/html');
                   10996:         $request->send_http_header;
                   10997:         return OK;
1.41      ng       10998:     }
                   10999:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  11000: 
1.596.2.12.2.  1(raebur 11001:0): # see what command we need to execute
                   11002:0):  
1.160     albertel 11003:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11004:     my $command=$commands[0];
1.447     foxr     11005: 
1.596.2.12.2.  1(raebur 11006:0):     &init_perm();
                   11007:0):     if (!$env{'request.course.id'}) {
                   11008:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11009:0):                 ($command =~ /^scantronupload/)) {
                   11010:0):             # Not in a course.
                   11011:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11012:0):             return HTTP_NOT_ACCEPTABLE;
                   11013:0):         }
                   11014:0):     } elsif (!%perm) {
                   11015:0):         $request->internal_redirect('/adm/quickgrades');
                   11016:0):         return OK;
                   11017:0):     }
                   11018:0):     &Apache::loncommon::content_type($request,'text/html');
                   11019:0):     $request->send_http_header;
                   11020:0): 
1.160     albertel 11021:     if ($#commands > 0) {
                   11022: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11023:     }
1.447     foxr     11024: 
1.596.2.12.2.  1(raebur 11025:0): # see what the symb is
                   11026:0): 
                   11027:0):     my $symb=$env{'form.symb'};
                   11028:0):     unless ($symb) {
                   11029:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11030:0):        $symb=&Apache::lonnet::symbread($url);
                   11031:0):     }
                   11032:0):     &Apache::lonenc::check_decrypt(\$symb);
                   11033:0): 
1.513     foxr     11034:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 11035:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   11036:0): #
                   11037:0): # Not called from a resource, but inside a course
                   11038:0): #
                   11039:0):         &startpage($request,undef,[],1,1);
                   11040:0):         &select_problem($request);
1.41      ng       11041:     } else {
1.596.2.12.2.  1(raebur 11042:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   11043:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 11044:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11045:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11046:):                     &choose_task_version_form($symb,$env{'form.student'},
                   11047:):                                               $env{'form.userdom'});
                   11048:):             }
          1(raebur 11049:0):             my $divforres;
                   11050:0):             if ($env{'form.student'} eq '') {
                   11051:0):                 $js .= &part_selector_js();
                   11052:0):                 $onload = "toggleParts('gradesub');";
                   11053:0):             } else {
                   11054:0):                 $divforres = 1;
                   11055:0):             }
          5(raebur 11056:0):             my $head_extra = $js;
                   11057:0):             unless ($env{'form.vProb'} eq 'no') {
                   11058:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11059:0):                 if ($csslinks) {
                   11060:0):                     $head_extra .= "\n$csslinks";
                   11061:0):                 }
                   11062:0):             }
                   11063:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,
                   11064:0):                        $stuvcurrent,$stuvdisp,undef,$head_extra,$onload,$divforres);
          (raeburn 11065:):             if ($versionform) {
          2(raebur 11066:0):                 if ($divforres) {
                   11067:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   11068:0):                 }
          (raeburn 11069:):                 $request->print($versionform);
                   11070:):             }
          1(raebur 11071:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 11072:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11073:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11074:):                 &choose_task_version_form($symb,$env{'form.student'},
                   11075:):                                           $env{'form.userdom'},
                   11076:):                                           $env{'form.inhibitmenu'});
          5(raebur 11077:0):             my $head_extra = $js;
                   11078:0):             unless ($env{'form.vProb'} eq 'no') {
                   11079:0):                 my $csslinks = &Apache::loncommon::css_links($symb);
                   11080:0):                 if ($csslinks) {
                   11081:0):                     $head_extra .= "\n$csslinks";
                   11082:0):                 }
                   11083:0):             }
                   11084:0):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,
                   11085:0):                        $stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$head_extra);
          (raeburn 11086:):             if ($versionform) {
                   11087:):                 $request->print($versionform);
                   11088:):             }
                   11089:):             $request->print('<br clear="all" />');
                   11090:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 11091:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   11092:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11093:0):                                        {href=>'',text=>'Select student'}],1,1);
                   11094:0):             &pickStudentPage($request,$symb);
                   11095:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
          5(raebur 11096:0):             my $csslinks;
                   11097:0):             unless ($env{'form.vProb'} eq 'no') {
                   11098:0):                 $csslinks = &Apache::loncommon::css_links($symb,'map');
                   11099:0):             }
          1(raebur 11100:0):             &startpage($request,$symb,
                   11101:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11102:0):                                        {href=>'',text=>'Select student'},
          5(raebur 11103:0):                                        {href=>'',text=>'Grade student'}],1,1,undef,undef,undef,$csslinks);
          1(raebur 11104:0):             &displayPage($request,$symb);
                   11105:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   11106:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11107:0):                                        {href=>'',text=>'Select student'},
                   11108:0):                                        {href=>'',text=>'Grade student'},
                   11109:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   11110:0):             &updateGradeByPage($request,$symb);
                   11111:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
          5(raebur 11112:0):             my $csslinks;
                   11113:0):             unless ($env{'form.vProb'} eq 'no') {
                   11114:0):                 $csslinks = &Apache::loncommon::css_links($symb);
                   11115:0):             }
          1(raebur 11116:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
          5(raebur 11117:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,$csslinks,undef,1);
          1(raebur 11118:0):             &processGroup($request,$symb);
                   11119:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   11120:0):             &startpage($request,$symb);
                   11121:0):             $request->print(&grading_menu($request,$symb));
                   11122:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   11123:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   11124:0):             $request->print(&submit_options($request,$symb));
                   11125:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   11126:0):             my $js = &part_selector_js();
                   11127:0):             my $onload = "toggleParts('gradesub');";
                   11128:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   11129:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11130:0):             $request->print(&listStudents($request,$symb,'graded'));
                   11131:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   11132:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   11133:0):             $request->print(&submit_options_table($request,$symb));
                   11134:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   11135:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   11136:0):             $request->print(&submit_options_sequence($request,$symb));
                   11137:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   11138:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   11139:0):             $request->print(&viewgrades($request,$symb));
                   11140:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   11141:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11142:0):                                        {href=>'',text=>'Store grades'}]);
                   11143:0):             $request->print(&processHandGrade($request,$symb));
                   11144:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   11145:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11146:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11147:0):                                                                              text=>"Modify grades"},
                   11148:0):                                        {href=>'', text=>"Store grades"}]);
                   11149:0):             $request->print(&editgrades($request,$symb));
                   11150:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   11151:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   11152:0):             $request->print(&initialverifyreceipt($request,$symb));
                   11153:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   11154:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11155:0):                                        {href=>'',text=>'Verification Result'}]);
                   11156:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      11157:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11158:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   11159:0):             $request->print(&process_clicker($request,$symb));
1.400     www      11160:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11161:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11162:0):                                        {href=>'', text=>'Process clicker file'}]);
                   11163:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      11164:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 11165:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11166:0):                                        {href=>'', text=>'Process clicker file'},
                   11167:0):                                        {href=>'', text=>'Store grades'}]);
                   11168:0):             $request->print(&assign_clicker_grades($request,$symb));
                   11169:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   11170:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11171:0):             $request->print(&upcsvScores_form($request,$symb));
                   11172:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   11173:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11174:0):             $request->print(&csvupload($request,$symb));
                   11175:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   11176:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11177:0):             $request->print(&csvuploadmap($request,$symb));
                   11178:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   11179:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   11180:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11181:0):                 $request->print(&csvuploadoptions($request,$symb));
                   11182:0):             } else {
                   11183:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11184:0):                     $env{'form.upfile_associate'} = 'reverse';
                   11185:0):                 } else {
                   11186:0):                     $env{'form.upfile_associate'} = 'forward';
                   11187:0):                 }
                   11188:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11189:0):                 $request->print(&csvuploadmap($request,$symb));
                   11190:0):             }
                   11191:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   11192:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   11193:0):             $request->print(&csvuploadassign($request,$symb));
                   11194:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   11195:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11196:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11197:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   11198:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   11199:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11200:0):             $request->print(&scantron_do_warning($request,$symb));
                   11201:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11202:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11203:0):             $request->print(&scantron_validate_file($request,$symb));
                   11204:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11205:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11206:0):             $request->print(&scantron_process_students($request,$symb));
                   11207:0):         } elsif ($command eq 'scantronupload' &&
                   11208:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11209:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11210:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11211:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11212:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11213:0):         } elsif ($command eq 'scantronupload_save' &&
                   11214:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11215:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11216:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11217:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11218:0):         } elsif ($command eq 'scantron_download' &&
                   11219:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11220:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11221:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11222:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11223:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11224:0):             $request->print(&checkscantron_results($request,$symb));
                   11225:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11226:0):             my $js = &part_selector_js();
                   11227:0):             my $onload = "toggleParts('gradingMenu');";
                   11228:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11229:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11230:0):             $request->print(&submit_options_download($request,$symb));
                   11231:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11232:0):             &startpage($request,$symb,
                   11233:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11234:0):     {href=>'', text=>'Download submitted files'}],
                   11235:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11236:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11237:0):             &submit_download_link($request,$symb);
                   11238:0):         } elsif ($command) {
                   11239:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11240:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11241:0):         }
1.2       albertel 11242:     }
1.513     foxr     11243:     if ($ssi_error) {
                   11244: 	&ssi_print_error($request);
                   11245:     }
1.353     albertel 11246:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11247:     &reset_caches();
1.596.2.4  raeburn  11248:     return OK;
1.44      ng       11249: }
                   11250: 
1.1       albertel 11251: 1;
                   11252: 
1.13      albertel 11253: __END__;
1.531     jms      11254: 
                   11255: 
                   11256: =head1 NAME
                   11257: 
                   11258: Apache::grades
                   11259: 
                   11260: =head1 SYNOPSIS
                   11261: 
                   11262: Handles the viewing of grades.
                   11263: 
                   11264: This is part of the LearningOnline Network with CAPA project
                   11265: described at http://www.lon-capa.org.
                   11266: 
                   11267: =head1 OVERVIEW
                   11268: 
                   11269: Do an ssi with retries:
                   11270: While I'd love to factor out this with the vesrion in lonprintout,
                   11271: 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
                   11272: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11273: 
                   11274: At least the logic that drives this has been pulled out into loncommon.
                   11275: 
                   11276: 
                   11277: 
                   11278: ssi_with_retries - Does the server side include of a resource.
                   11279:                      if the ssi call returns an error we'll retry it up to
                   11280:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11281:4):                      If we still have a problem, no text is appended to the
1.531     jms      11282:                      output and we set some global variables.
                   11283:                      to indicate to the caller an SSI error occurred.  
                   11284:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11285:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11286:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11287:                      by informing the user that this happened.
                   11288: 
                   11289: Parameters:
                   11290:   resource   - The resource to include.  This is passed directly, without
                   11291:                interpretation to lonnet::ssi.
                   11292:   form       - The form hash parameters that guide the interpretation of the resource
                   11293:                
                   11294:   retries    - Number of retries allowed before giving up completely.
                   11295: Returns:
                   11296:   On success, returns the rendered resource identified by the resource parameter.
                   11297: Side Effects:
                   11298:   The following global variables can be set:
                   11299:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11300:                               It is up to the caller to initialize this to false
                   11301:                               if desired.
                   11302:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11303:                               of the resource that could not be rendered by the ssi
                   11304:                               call.
                   11305:    ssi_error_message   - The error string fetched from the ssi response
                   11306:                               in the event of an error.
                   11307: 
                   11308: 
                   11309: =head1 HANDLER SUBROUTINE
                   11310: 
                   11311: ssi_with_retries()
                   11312: 
                   11313: =head1 SUBROUTINES
                   11314: 
                   11315: =over
                   11316: 
                   11317: =item scantron_get_correction() : 
                   11318: 
                   11319:    Builds the interface screen to interact with the operator to fix a
                   11320:    specific error condition in a specific scanline
                   11321: 
                   11322:  Arguments:
                   11323:     $r           - Apache request object
                   11324:     $i           - number of the current scanline
                   11325:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11326:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11327:     $line        - full contents of the current scanline
                   11328:     $error       - error condition, valid values are
                   11329:                    'incorrectCODE', 'duplicateCODE',
                   11330:                    'doublebubble', 'missingbubble',
                   11331:                    'duplicateID', 'incorrectID'
                   11332:     $arg         - extra information needed
                   11333:        For errors:
                   11334:          - duplicateID   - paper number that this studentID was seen before on
                   11335:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11336:                            seen on before
                   11337:          - incorrectCODE - current incorrect CODE 
                   11338:          - doublebubble  - array ref of the bubble lines that have double
                   11339:                            bubble errors
                   11340:          - missingbubble - array ref of the bubble lines that have missing
                   11341:                            bubble errors
                   11342: 
1.596.2.12.2.  0(raebur 11343:2):    $randomorder - True if exam folder (or a sub-folder) has randomorder set
                   11344:2):    $randompick  - True if exam folder (or a sub-folder) has randompick set
          6(raebur 11345:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11346:3):                      for current line to question number used for same question
                   11347:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11348:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11349:3):                   and value is number of first bubble line for current student
                   11350:3):                   or code-based randompick and/or randomorder.
                   11351:3): 
                   11352:3): 
1.531     jms      11353: =item  scantron_get_maxbubble() : 
                   11354: 
1.582     raeburn  11355:    Arguments:
                   11356:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11357:                       failure to retrieve a navmap object.
                   11358:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11359:        calling routine should trap the error condition and display the warning
                   11360:        found in &navmap_errormsg().
                   11361: 
1.596.2.12.2.  (raeburn 11362:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11363:): 
1.531     jms      11364:    Returns the maximum number of bubble lines that are expected to
                   11365:    occur. Does this by walking the selected sequence rendering the
                   11366:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11367:    for what the current value of the problem counter is.
                   11368: 
                   11369:    Caches the results to $env{'form.scantron_maxbubble'},
                   11370:    $env{'form.scantron.bubble_lines.n'}, 
                   11371:    $env{'form.scantron.first_bubble_line.n'} and
                   11372:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11373:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11374:    lines for response n and number of the first bubble line for response n,
                   11375:    and a comma separated list of numbers of bubble lines for sub-questions
                   11376:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11377: 
                   11378: 
                   11379: =item  scantron_validate_missingbubbles() : 
                   11380: 
                   11381:    Validates all scanlines in the selected file to not have any
                   11382:     answers that don't have bubbles that have not been verified
                   11383:     to be bubble free.
                   11384: 
                   11385: =item  scantron_process_students() : 
                   11386: 
1.596.2.6  raeburn  11387:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11388: 
                   11389:    The parsed scanline hash is added to %env 
                   11390: 
                   11391:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11392:    foreach resource , with the form data of
                   11393: 
                   11394: 	'submitted'     =>'scantron' 
                   11395: 	'grade_target'  =>'grade',
                   11396: 	'grade_username'=> username of student
                   11397: 	'grade_domain'  => domain of student
                   11398: 	'grade_courseid'=> of course
                   11399: 	'grade_symb'    => symb of resource to grade
                   11400: 
                   11401:     This triggers a grading pass. The problem grading code takes care
                   11402:     of converting the bubbled letter information (now in %env) into a
                   11403:     valid submission.
                   11404: 
                   11405: =item  scantron_upload_scantron_data() :
                   11406: 
1.596.2.6  raeburn  11407:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11408: 
                   11409: =item  scantron_upload_scantron_data_save() : 
                   11410: 
                   11411:    Adds a provided bubble information data file to the course if user
                   11412:    has the correct privileges to do so. 
                   11413: 
                   11414: =item  valid_file() :
                   11415: 
                   11416:    Validates that the requested bubble data file exists in the course.
                   11417: 
                   11418: =item  scantron_download_scantron_data() : 
                   11419: 
                   11420:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11421:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11422:    course.
                   11423: 
                   11424: =item  scantron_validate_ID() : 
                   11425: 
                   11426:    Validates all scanlines in the selected file to not have any
1.556     weissno  11427:    invalid or underspecified student/employee IDs
1.531     jms      11428: 
1.582     raeburn  11429: =item navmap_errormsg() :
                   11430: 
                   11431:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11432:    Should be called whenever the request to instantiate a navmap object fails.  
                   11433: 
1.531     jms      11434: =back
                   11435: 
                   11436: =cut

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