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

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.  3(raebur    4:0): # $Id: grades.pm,v 1.596.2.12.2.52 2020/09/08 14:09:30 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'))
                   1146:                   .$submission_options
1.596.2.12.2.  1(raebur 1147:0):                   .&Apache::lonhtmlcommon::row_closure()
                   1148:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1149:0):                   .'<span class="LC_nobreak">'
                   1150:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1151:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1152:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1153:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1154:                   .&Apache::lonhtmlcommon::row_closure();
                   1155: 
                   1156:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1157:                   .'<select name="increment">'
                   1158:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1159:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1160:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1161:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1162:0):                   .'</select>';
1.485     albertel 1163:     $gradeTable .= 
1.432     banghart 1164:         &build_section_inputs().
1.45      ng       1165: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1166: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1167: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1168:0):     if (exists($env{'form.Status'})) {
1.561     bisitz   1169: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1170:     } else {
1.596.2.12.2.  1(raebur 1171:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1172:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1173:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1174:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1175:     }
1.596.2.12.2.  1(raebur 1176:0):     if ($numessay) {
                   1177:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1178:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1179:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1180:0):     }
                   1181:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1182:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1183: 
                   1184:     $gradeTable .= '<p>'
1.596.2.12.2.  1(raebur 1185: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   1186:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1187:                   .'</p>';
1.249     albertel 1188: 
                   1189: # checkall buttons
                   1190:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1191:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1192:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1193:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1194:     $gradeTable.=&check_buttons();
1.450     banghart 1195:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1196:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1197: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1198:     my $loop = 0;
                   1199:     while ($loop < 2) {
1.485     albertel 1200: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1201: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1202:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1203: 	    foreach my $part (sort(@$partlist)) {
                   1204: 		my $display_part=
                   1205: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1206: 		$gradeTable.=
                   1207: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1208: 	    }
1.301     albertel 1209: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1210: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1211: 	}
                   1212: 	$loop++;
1.126     ng       1213: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1214:     }
1.474     albertel 1215:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1216: 
1.45      ng       1217:     my $ctr = 0;
1.294     albertel 1218:     foreach my $student (sort 
                   1219: 			 {
                   1220: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1221: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1222: 			     }
                   1223: 			     return $a cmp $b;
                   1224: 			 }
                   1225: 			 (keys(%$fullname))) {
1.41      ng       1226: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1227: 
1.110     ng       1228: 	my %status = ();
1.301     albertel 1229: 
                   1230: 	if ($submitonly eq 'queued') {
                   1231: 	    my %queue_status = 
                   1232: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1233: 							$udom,$uname);
                   1234: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1235: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1236: 	}
                   1237: 
1.596.2.12.2.  1(raebur 1238:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1239: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1240: 	    my $submitted = 0;
1.164     albertel 1241: 	    my $graded = 0;
1.248     albertel 1242: 	    my $incorrect = 0;
1.110     ng       1243: 	    foreach (keys(%status)) {
1.145     albertel 1244: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1245: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1246: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1247: 		
1.110     ng       1248: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1249: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1250: 		    $submitted = 0;
1.150     albertel 1251: 		    my ($part)=split(/\./,$partid);
1.110     ng       1252: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1253: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1254: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1255: 		}
1.41      ng       1256: 	    }
1.248     albertel 1257: 	    
1.156     albertel 1258: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1259: 				     $submitonly eq 'incorrect' ||
                   1260: 				     $submitonly eq 'graded'));
1.248     albertel 1261: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1262: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1263: 	}
1.34      ng       1264: 
1.45      ng       1265: 	$ctr++;
1.249     albertel 1266: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1267:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1268: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1269: 	    if ($ctr%2 ==1) {
                   1270: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1271: 	    }
1.126     ng       1272: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1273:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1274:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1275: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1276: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1277: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1278: 
1.596.2.12.2.  1(raebur 1279:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1280: 		foreach (sort(keys(%status))) {
1.485     albertel 1281: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1282: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1283: 		}
1.41      ng       1284: 	    }
1.126     ng       1285: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1286: 	    if ($ctr%2 ==0) {
                   1287: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1288: 	    }
1.41      ng       1289: 	}
                   1290:     }
1.110     ng       1291:     if ($ctr%2 ==1) {
1.126     ng       1292: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1293:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1294: 		foreach (@$partlist) {
                   1295: 		    $gradeTable.='<td>&nbsp;</td>';
                   1296: 		}
1.301     albertel 1297: 	    } elsif ($submitonly eq 'queued') {
                   1298: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1299: 	    }
1.474     albertel 1300: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1301:     }
                   1302: 
1.474     albertel 1303:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1304:         '<input type="button" '.
                   1305:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1306:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1307:     if ($ctr == 0) {
1.96      albertel 1308: 	my $num_students=(scalar(keys(%$fullname)));
                   1309: 	if ($num_students eq 0) {
1.485     albertel 1310: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1311: 	} else {
1.171     albertel 1312: 	    my $submissions='submissions';
                   1313: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1314: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1315: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1316: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1317:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1318: 		    $num_students).
                   1319: 		'</span><br />';
1.96      albertel 1320: 	}
1.46      ng       1321:     } elsif ($ctr == 1) {
1.474     albertel 1322: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1323:     }
                   1324:     $request->print($gradeTable);
1.44      ng       1325:     return '';
1.10      ng       1326: }
                   1327: 
1.44      ng       1328: #---- Called from the listStudents routine
1.249     albertel 1329: 
                   1330: sub check_script {
1.596.2.12.2.  1(raebur 1331:0):     my ($form,$type) = @_;
                   1332:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1333:     function checkall() {
                   1334:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1335:             ele = document.forms.'.$form.'.elements[i];
                   1336:             if (ele.name == "'.$type.'") {
                   1337:             document.forms.'.$form.'.elements[i].checked=true;
                   1338:                                        }
                   1339:         }
                   1340:     }
                   1341: 
                   1342:     function checksec() {
                   1343:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1344:             ele = document.forms.'.$form.'.elements[i];
                   1345:            string = document.forms.'.$form.'.chksec.value;
                   1346:            if
                   1347:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1348:               document.forms.'.$form.'.elements[i].checked=true;
                   1349:             }
                   1350:         }
                   1351:     }
                   1352: 
                   1353: 
                   1354:     function uncheckall() {
                   1355:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1356:             ele = document.forms.'.$form.'.elements[i];
                   1357:             if (ele.name == "'.$type.'") {
                   1358:             document.forms.'.$form.'.elements[i].checked=false;
                   1359:                                        }
                   1360:         }
                   1361:     }
                   1362: 
1.596.2.12.2.  1(raebur 1363:0): '."\n");
1.249     albertel 1364:     return $chkallscript;
                   1365: }
                   1366: 
                   1367: sub check_buttons {
1.485     albertel 1368:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1369:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1370:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1371:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1372:     return $buttons;
                   1373: }
                   1374: 
1.44      ng       1375: #     Displays the submissions for one student or a group of students
1.34      ng       1376: sub processGroup {
1.596.2.12.2.  1(raebur 1377:0):     my ($request,$symb) = @_;
1.41      ng       1378:     my $ctr        = 0;
1.155     albertel 1379:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1380:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1381: 
1.396     banghart 1382:     foreach my $student (@stuchecked) {
                   1383: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1384: 	$env{'form.student'}        = $uname;
                   1385: 	$env{'form.userdom'}        = $udom;
                   1386: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1387:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1388: 	$ctr++;
                   1389:     }
                   1390:     return '';
1.35      ng       1391: }
1.34      ng       1392: 
1.44      ng       1393: #------------------------------------------------------------------------------------
                   1394: #
                   1395: #-------------------------- Next few routines handles grading by student, essentially
                   1396: #                           handles essay response type problem/part
                   1397: #
                   1398: #--- Javascript to handle the submission page functionality ---
                   1399: sub sub_page_js {
                   1400:     my $request = shift;
1.596.2.12.2.  6(raebur 1401:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1402:6):     &js_escape(\$alertmsg);
          1(raebur 1403:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1404:     function updateRadio(formname,id,weight) {
1.125     ng       1405: 	var gradeBox = formname["GD_BOX"+id];
                   1406: 	var radioButton = formname["RADVAL"+id];
                   1407: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1408: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1409: 	gradeBox.value = pts;
                   1410: 	var resetbox = false;
                   1411: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1412: 	    alert("$alertmsg"+pts);
1.71      ng       1413: 	    for (var i=0; i<radioButton.length; i++) {
                   1414: 		if (radioButton[i].checked) {
                   1415: 		    gradeBox.value = i;
                   1416: 		    resetbox = true;
                   1417: 		}
                   1418: 	    }
                   1419: 	    if (!resetbox) {
                   1420: 		formtextbox.value = "";
                   1421: 	    }
                   1422: 	    return;
1.44      ng       1423: 	}
1.71      ng       1424: 
                   1425: 	if (pts > weight) {
                   1426: 	    var resp = confirm("You entered a value ("+pts+
                   1427: 			       ") greater than the weight for the part. Accept?");
                   1428: 	    if (resp == false) {
1.125     ng       1429: 		gradeBox.value = oldpts;
1.71      ng       1430: 		return;
                   1431: 	    }
1.44      ng       1432: 	}
1.13      albertel 1433: 
1.71      ng       1434: 	for (var i=0; i<radioButton.length; i++) {
                   1435: 	    radioButton[i].checked=false;
                   1436: 	    if (pts == i && pts != "") {
                   1437: 		radioButton[i].checked=true;
                   1438: 	    }
                   1439: 	}
                   1440: 	updateSelect(formname,id);
1.125     ng       1441: 	formname["stores"+id].value = "0";
1.41      ng       1442:     }
1.5       albertel 1443: 
1.72      ng       1444:     function writeBox(formname,id,pts) {
1.125     ng       1445: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1446: 	if (checkSolved(formname,id) == 'update') {
                   1447: 	    gradeBox.value = pts;
                   1448: 	} else {
1.125     ng       1449: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1450: 	    gradeBox.value = oldpts;
1.125     ng       1451: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1452: 	    for (var i=0; i<radioButton.length; i++) {
                   1453: 		radioButton[i].checked=false;
1.72      ng       1454: 		if (i == oldpts) {
1.71      ng       1455: 		    radioButton[i].checked=true;
                   1456: 		}
                   1457: 	    }
1.41      ng       1458: 	}
1.125     ng       1459: 	formname["stores"+id].value = "0";
1.71      ng       1460: 	updateSelect(formname,id);
                   1461: 	return;
1.41      ng       1462:     }
1.44      ng       1463: 
1.71      ng       1464:     function clearRadBox(formname,id) {
                   1465: 	if (checkSolved(formname,id) == 'noupdate') {
                   1466: 	    updateSelect(formname,id);
                   1467: 	    return;
                   1468: 	}
1.125     ng       1469: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1470: 	for (var i=0; i<gradeSelect.length; i++) {
                   1471: 	    if (gradeSelect[i].selected) {
                   1472: 		var selectx=i;
                   1473: 	    }
                   1474: 	}
1.125     ng       1475: 	var stores = formname["stores"+id];
1.71      ng       1476: 	if (selectx == stores.value) { return };
1.125     ng       1477: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1478: 	gradeBox.value = "";
1.125     ng       1479: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1480: 	for (var i=0; i<radioButton.length; i++) {
                   1481: 	    radioButton[i].checked=false;
                   1482: 	}
                   1483: 	stores.value = selectx;
                   1484:     }
1.5       albertel 1485: 
1.71      ng       1486:     function checkSolved(formname,id) {
1.125     ng       1487: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1488: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1489: 	    if (!reply) {return "noupdate";}
1.120     ng       1490: 	    formname.overRideScore.value = 'yes';
1.41      ng       1491: 	}
1.71      ng       1492: 	return "update";
1.13      albertel 1493:     }
1.71      ng       1494: 
                   1495:     function updateSelect(formname,id) {
1.125     ng       1496: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1497: 	return;
1.41      ng       1498:     }
1.33      ng       1499: 
1.121     ng       1500: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1501:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1502: 	formname.gradeOpt.value = val;
1.71      ng       1503: 	if (val == "Save & Next") {
                   1504: 	    for (i=0;i<=total;i++) {
                   1505: 		for (j=0;j<parttot;j++) {
1.125     ng       1506: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1507: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1508: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1509: 			if (points == "") {
1.125     ng       1510: 			    var name = formname["name"+i].value;
1.129     ng       1511: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1512: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1513: 					       ", part "+partid+". Continue?");
1.71      ng       1514: 			    if (resp == false) {
1.125     ng       1515: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1516: 				return false;
                   1517: 			    }
                   1518: 			}
                   1519: 		    }
                   1520: 		}
                   1521: 	    }
                   1522: 	}
1.120     ng       1523: 	formname.submit();
                   1524:     }
                   1525: 
1.71      ng       1526: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1527:     function checkSubmitPage(formname,total) {
                   1528: 	noscore = new Array(100);
                   1529: 	var ptr = 0;
                   1530: 	for (i=1;i<total;i++) {
1.125     ng       1531: 	    var partid = formname["q_"+i].value;
1.127     ng       1532: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1533: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1534: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1535: 		if (points == "" && status != "correct_by_student") {
                   1536: 		    noscore[ptr] = i;
                   1537: 		    ptr++;
                   1538: 		}
                   1539: 	    }
                   1540: 	}
                   1541: 	if (ptr != 0) {
                   1542: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1543: 	    var prolist = "";
                   1544: 	    if (ptr == 1) {
                   1545: 		prolist = noscore[0];
                   1546: 	    } else {
                   1547: 		var i = 0;
                   1548: 		while (i < ptr-1) {
                   1549: 		    prolist += noscore[i]+", ";
                   1550: 		    i++;
                   1551: 		}
                   1552: 		prolist += "and "+noscore[i];
                   1553: 	    }
                   1554: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1555: 	    if (resp == false) {
                   1556: 		return false;
                   1557: 	    }
                   1558: 	}
1.45      ng       1559: 
1.71      ng       1560: 	formname.submit();
                   1561:     }
                   1562: SUBJAVASCRIPT
                   1563: }
1.45      ng       1564: 
1.596.2.12.2.  1(raebur 1565:0): #--- javascript for grading message center
                   1566:0): sub sub_grademessage_js {
1.71      ng       1567:     my $request = shift;
1.80      ng       1568:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1569:     &commonJSfunctions($request);
1.350     albertel 1570: 
1.596.2.12.2.  1(raebur 1571:0):     my $inner_js_msg_central= (<<INNERJS);
                   1572:0): <script type="text/javascript">
1.350     albertel 1573:     function checkInput() {
                   1574:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1575:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1576:       var usrctr = document.msgcenter.usrctr.value;
                   1577:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1578:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1579: 
                   1580:       var msgchk = "";
                   1581:       if (document.msgcenter.subchk.checked) {
                   1582:          msgchk = "msgsub,";
                   1583:       }
                   1584:       var includemsg = 0;
                   1585:       for (var i=1; i<=nmsg; i++) {
                   1586:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1587:           var frmmsg = document.msgcenter["msg"+i];
                   1588:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1589:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1590:           showflg.value = "1";
                   1591:           var chkbox = document.msgcenter["msgn"+i];
                   1592:           if (chkbox.checked) {
                   1593:              msgchk += "savemsg"+i+",";
                   1594:              includemsg = 1;
                   1595:           }
                   1596:       }
                   1597:       if (document.msgcenter.newmsgchk.checked) {
                   1598:          msgchk += "newmsg"+usrctr;
                   1599:          includemsg = 1;
                   1600:       }
                   1601:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1602:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1603:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1604:       includemsg.value = msgchk;
                   1605: 
                   1606:       self.close()
                   1607: 
                   1608:     }
1.351     albertel 1609: </script>
                   1610: INNERJS
                   1611: 
1.596.2.12.2.  1(raebur 1612:0):     my $start_page_msg_central =
1.351     albertel 1613:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1614: 				       {'js_ready'  => 1,
                   1615: 					'only_body' => 1,
                   1616: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1617:0):     my $end_page_msg_central =
1.351     albertel 1618: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1619: 
                   1620: 
1.219     www      1621:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1622:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1623:0): 
          6(raebur 1624:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1625:                 comp => 'Compose Message for: ',
                   1626:                 incl => 'Include',
                   1627:                 type => 'Type',
                   1628:                 subj => 'Subject',
                   1629:                 mesa => 'Message',
                   1630:                 new  => 'New',
                   1631:                 save => 'Save',
                   1632:                 canc => 'Cancel',
                   1633:              );
1.596.2.12.2.  6(raebur 1634:6):     &html_escape(\%html_js_lt);
                   1635:6):     &js_escape(\%html_js_lt);
          1(raebur 1636:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1637: 
                   1638: //===================== Script to view submitted by ==================
                   1639:   function viewSubmitter(submitter) {
                   1640:     document.SCORE.refresh.value = "on";
                   1641:     document.SCORE.NCT.value = "1";
                   1642:     document.SCORE.unamedom0.value = submitter;
                   1643:     document.SCORE.submit();
                   1644:     return;
                   1645:   }
                   1646: 
                   1647: //====================== Script for composing message ==============
1.80      ng       1648:    // preload images
                   1649:    img1 = new Image();
                   1650:    img1.src = "$iconpath/mailbkgrd.gif";
                   1651:    img2 = new Image();
                   1652:    img2.src = "$iconpath/mailto.gif";
                   1653: 
1.44      ng       1654:   function msgCenter(msgform,usrctr,fullname) {
                   1655:     var Nmsg  = msgform.savemsgN.value;
                   1656:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1657:     var subject = msgform.msgsub.value;
1.127     ng       1658:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1659:     re = /msgsub/;
                   1660:     var shwsel = "";
                   1661:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1662:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1663:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1664:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1665: 	var testmsg = "savemsg"+i+",";
                   1666: 	re = new RegExp(testmsg,"g");
1.44      ng       1667: 	shwsel = "";
                   1668: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1669: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1670: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1671: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1672: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1673:     }
1.125     ng       1674:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1675:     shwsel = "";
                   1676:     re = /newmsg/;
                   1677:     if (re.test(msgchk)) { shwsel = "checked" }
                   1678:     newMsg(newmsg,shwsel);
                   1679:     msgTail(); 
                   1680:     return;
                   1681:   }
                   1682: 
1.123     ng       1683:   function checkEntities(strx) {
                   1684:     if (strx.length == 0) return strx;
                   1685:     var orgStr = ["&", "<", ">", '"']; 
                   1686:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1687:     var counter = 0;
                   1688:     while (counter < 4) {
                   1689: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1690: 	counter++;
                   1691:     }
                   1692:     return strx;
                   1693:   }
                   1694: 
                   1695:   function strReplace(strx, orgStr, newStr) {
                   1696:     return strx.split(orgStr).join(newStr);
                   1697:   }
                   1698: 
1.44      ng       1699:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1700:     var height = 70*Nmsg+250;
1.44      ng       1701:     if (height > 600) {
                   1702: 	height = 600;
                   1703:     }
1.118     ng       1704:     var xpos = (screen.width-600)/2;
                   1705:     xpos = (xpos < 0) ? '0' : xpos;
                   1706:     var ypos = (screen.height-height)/2-30;
                   1707:     ypos = (ypos < 0) ? '0' : ypos;
                   1708: 
1.596.2.12.2.  (raeburn 1709:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1710:     pWin.focus();
                   1711:     pDoc = pWin.document;
1.219     www      1712:     pDoc.$docopen;
1.351     albertel 1713:     pDoc.write('$start_page_msg_central');
1.76      ng       1714: 
                   1715:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1716:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1717:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1718: 
1.596.2.12.2.  1(raebur 1719:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1720: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       1721: }
                   1722:     function displaySubject(msg,shwsel) {
1.76      ng       1723:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1724:0):     pDoc.write("<tr>");
1.465     albertel 1725:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1726:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1727:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1728: }
                   1729: 
1.72      ng       1730:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1731:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1732:0):     pDoc.write("<tr>");
1.465     albertel 1733:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1734:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1735:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1736: }
                   1737: 
                   1738:   function newMsg(newmsg,shwsel) {
1.76      ng       1739:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1740:0):     pDoc.write("<tr>");
1.465     albertel 1741:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1742:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1743:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1744: }
                   1745: 
                   1746:   function msgTail() {
1.76      ng       1747:     pDoc = pWin.document;
1.465     albertel 1748:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1749:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1750:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1751:     pDoc.write("<\\/form>");
1.351     albertel 1752:     pDoc.write('$end_page_msg_central');
1.128     ng       1753:     pDoc.close();
1.44      ng       1754: }
                   1755: 
1.596.2.12.2.  1(raebur 1756:0): SUBJAVASCRIPT
                   1757:0): }
                   1758:0): 
                   1759:0): #--- javascript for essay type problem --
                   1760:0): sub sub_page_kw_js {
                   1761:0):     my $request = shift;
                   1762:0): 
                   1763:0):     unless ($env{'form.compmsg'}) {
                   1764:0):         &commonJSfunctions($request);
                   1765:0):     }
                   1766:0): 
                   1767:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1768:0): <script type="text/javascript">
                   1769:0):     function updateChoice(flag) {
                   1770:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1771:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1772:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1773:0):       opener.document.SCORE.refresh.value = "on";
                   1774:0):       if (opener.document.SCORE.keywords.value!=""){
                   1775:0):          opener.document.SCORE.submit();
                   1776:0):       }
                   1777:0):       self.close()
                   1778:0):     }
                   1779:0): </script>
                   1780:0): INNERJS
                   1781:0): 
                   1782:0):     my $start_page_highlight_central =
                   1783:0):         &Apache::loncommon::start_page('Highlight Central',
                   1784:0):                                        $inner_js_highlight_central,
                   1785:0):                                        {'js_ready'  => 1,
                   1786:0):                                         'only_body' => 1,
                   1787:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1788:0):     my $end_page_highlight_central =
                   1789:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1790:0): 
                   1791:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1792:0):     $docopen=~s/^document\.//;
                   1793:0): 
                   1794:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1795:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1796:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1797:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1798:0):                 col1 => 'red',
                   1799:0):                 col2 => 'green',
                   1800:0):                 col3 => 'blue',
                   1801:0):                 siz1 => 'normal',
                   1802:0):                 siz2 => '+1',
                   1803:0):                 siz3 => '+2',
                   1804:0):                 sty1 => 'normal',
                   1805:0):                 sty2 => 'italic',
                   1806:0):                 sty3 => 'bold',
                   1807:0):              );
                   1808:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1809:0):                 save => 'Save',
                   1810:0):                 canc => 'Cancel',
                   1811:0):                 kehi => 'Keyword Highlight Options',
                   1812:0):                 txtc => 'Text Color',
                   1813:0):                 font => 'Font Size',
                   1814:0):                 fnst => 'Font Style',
                   1815:0):              );
                   1816:0):     &js_escape(\%js_lt);
                   1817:0):     &html_escape(\%html_js_lt);
                   1818:0):     &js_escape(\%html_js_lt);
                   1819:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1820:0): 
                   1821:0): //===================== Show list of keywords ====================
                   1822:0):   function keywords(formname) {
                   1823:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1824:0):     if (nret==null) return;
                   1825:0):     formname.keywords.value = nret;
                   1826:0): 
                   1827:0):     if (formname.keywords.value != "") {
                   1828:0):         formname.refresh.value = "on";
                   1829:0):         formname.submit();
                   1830:0):     }
                   1831:0):     return;
                   1832:0):   }
                   1833:0): 
                   1834:0): //===================== Script to add keyword(s) ==================
                   1835:0):   function getSel() {
                   1836:0):     if (document.getSelection) txt = document.getSelection();
                   1837:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1838:0):     else return;
                   1839:0):     if (typeof(txt) != 'string') {
                   1840:0):         txt = String(txt);
                   1841:0):     }
                   1842:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1843:0):     if (cleantxt=="") {
                   1844:0):         alert("$js_lt{'plse'}");
                   1845:0):         return;
                   1846:0):     }
                   1847:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1848:0):     if (nret==null) return;
                   1849:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1850:0):     if (document.SCORE.keywords.value != "") {
                   1851:0):         document.SCORE.refresh.value = "on";
                   1852:0):         document.SCORE.submit();
                   1853:0):     }
                   1854:0):     return;
                   1855:0):   }
                   1856:0): 
1.44      ng       1857: //====================== Script for keyword highlight options ==============
                   1858:   function kwhighlight() {
                   1859:     var kwclr    = document.SCORE.kwclr.value;
                   1860:     var kwsize   = document.SCORE.kwsize.value;
                   1861:     var kwstyle  = document.SCORE.kwstyle.value;
                   1862:     var redsel = "";
                   1863:     var grnsel = "";
                   1864:     var blusel = "";
1.596.2.12.2.  6(raebur 1865:6):     var txtcol1 = "$js_lt{'col1'}";
                   1866:6):     var txtcol2 = "$js_lt{'col2'}";
                   1867:6):     var txtcol3 = "$js_lt{'col3'}";
                   1868:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1869:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1870:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1871:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1872:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1873:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1874:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1875:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1876:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1877:     var sznsel = "";
                   1878:     var sz1sel = "";
                   1879:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1880:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1881:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1882:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1883:     var synsel = "";
                   1884:     var syisel = "";
                   1885:     var sybsel = "";
1.596.2.12.2.  8(raebur 1886:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1887:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1888:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1889:     highlightCentral();
1.596.2.12.2.  8(raebur 1890:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1891:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1892:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1893:     highlightend();
                   1894:     return;
                   1895:   }
                   1896: 
                   1897:   function highlightCentral() {
1.76      ng       1898: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1899:     var xpos = (screen.width-400)/2;
                   1900:     xpos = (xpos < 0) ? '0' : xpos;
                   1901:     var ypos = (screen.height-330)/2-30;
                   1902:     ypos = (ypos < 0) ? '0' : ypos;
                   1903: 
1.206     albertel 1904:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1905:     hwdWin.focus();
                   1906:     var hDoc = hwdWin.document;
1.219     www      1907:     hDoc.$docopen;
1.351     albertel 1908:     hDoc.write('$start_page_highlight_central');
1.76      ng       1909:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1910:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1911: 
1.596.2.12.2.  8(raebur 1912:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1913: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       1914:   }
                   1915: 
                   1916:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1917:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1918:4):     hDoc.write("<tr>");
1.76      ng       1919:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1920:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1921:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1922:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1923:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1924:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1925:     hDoc.write("<\\/tr>");
1.44      ng       1926:   }
                   1927: 
                   1928:   function highlightend() { 
1.76      ng       1929:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1930:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1931:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1932:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1933:     hDoc.write("<\\/form>");
1.351     albertel 1934:     hDoc.write('$end_page_highlight_central');
1.128     ng       1935:     hDoc.close();
1.44      ng       1936:   }
                   1937: 
                   1938: SUBJAVASCRIPT
                   1939: }
                   1940: 
1.349     albertel 1941: sub get_increment {
1.348     bowersj2 1942:     my $increment = $env{'form.increment'};
                   1943:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1944:         $increment != .1) {
                   1945:         $increment = 1;
                   1946:     }
                   1947:     return $increment;
                   1948: }
                   1949: 
1.585     bisitz   1950: sub gradeBox_start {
                   1951:     return (
                   1952:         &Apache::loncommon::start_data_table()
                   1953:        .&Apache::loncommon::start_data_table_header_row()
                   1954:        .'<th>'.&mt('Part').'</th>'
                   1955:        .'<th>'.&mt('Points').'</th>'
                   1956:        .'<th>&nbsp;</th>'
                   1957:        .'<th>'.&mt('Assign Grade').'</th>'
                   1958:        .'<th>'.&mt('Weight').'</th>'
                   1959:        .'<th>'.&mt('Grade Status').'</th>'
                   1960:        .&Apache::loncommon::end_data_table_header_row()
                   1961:     );
                   1962: }
                   1963: 
                   1964: sub gradeBox_end {
                   1965:     return (
                   1966:         &Apache::loncommon::end_data_table()
                   1967:     );
                   1968: }
1.71      ng       1969: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1970: sub gradeBox {
1.322     albertel 1971:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1972:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1973: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1974:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1975:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1976:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1977:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1978:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1979: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1980:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1981:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1982:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1983: 				       [$partid]);
                   1984:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1985:     if ($last_resets{$partid}) {
                   1986:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1987:     }
1.596.2.12.2.  8(raebur 1988:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1989:     my $ctr = 0;
1.348     bowersj2 1990:     my $thisweight = 0;
1.349     albertel 1991:     my $increment = &get_increment();
1.485     albertel 1992: 
                   1993:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1994:     while ($thisweight<=$wgt) {
1.532     bisitz   1995: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1996:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1997: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1998: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1999: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2000:         $thisweight += $increment;
1.71      ng       2001: 	$ctr++;
                   2002:     }
1.485     albertel 2003:     $radio.='</tr></table>';
                   2004: 
                   2005:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2006: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2007: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2008: 	$wgt.')" /></td>'."\n";
1.485     albertel 2009:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2010: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2011: 	' </td>'."\n";
                   2012:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2013: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2014:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2015: 	$line.='<option></option>'.
                   2016: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2017:     } else {
1.485     albertel 2018: 	$line.='<option selected="selected"></option>'.
                   2019: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2020:     }
1.485     albertel 2021:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2022: 
                   2023: 
                   2024:     $result .= 
1.596.2.12.2.  8(raebur 2025:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2026:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2027:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2028:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2029: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2030: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2031: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2032:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2033:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2034:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2035:         $aggtries.'" />'."\n";
1.582     raeburn  2036:     my $res_error;
                   2037:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2038:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2039:     if ($res_error) {
                   2040:         return &navmap_errormsg();
                   2041:     }
1.318     banghart 2042:     return $result;
                   2043: }
1.322     albertel 2044: 
                   2045: sub handback_box {
1.596.2.12.2.  1(raebur 2046:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2047:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2048:0):     return unless ($numessay);
1.323     banghart 2049:     my (@respids);
1.596.2.4  raeburn  2050:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2051:     foreach my $part_response_id (@part_response_id) {
                   2052:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2053:         if ($part eq $partid) {
1.375     albertel 2054:             push(@respids,$resp);
1.323     banghart 2055:         }
                   2056:     }
1.318     banghart 2057:     my $result;
1.323     banghart 2058:     foreach my $respid (@respids) {
1.322     albertel 2059: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2060: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2061: 	next if (!@$files);
1.596.2.4  raeburn  2062: 	my $file_counter = 0;
1.313     banghart 2063: 	foreach my $file (@$files) {
1.368     banghart 2064: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2065:                 $file_counter++;
1.368     banghart 2066:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2067:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2068:     	        $file_disp = "$name.$ext";
                   2069:     	        $file = $file_path.$file_disp;
                   2070:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2071:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2072:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2073:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2074: 	    }
1.322     albertel 2075: 	}
1.596.2.4  raeburn  2076:         if ($file_counter) {
                   2077:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2078:                        '<span class="LC_info">'.
                   2079:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2080:         }
1.313     banghart 2081:     }
1.318     banghart 2082:     return $result;    
1.71      ng       2083: }
1.44      ng       2084: 
1.58      albertel 2085: sub show_problem {
1.382     albertel 2086:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2087:     my $rendered;
1.382     albertel 2088:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2089:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2090:     if ($mode eq 'both' or $mode eq 'text') {
                   2091: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2092: 						       $env{'request.course.id'},
                   2093: 						       undef,\%form);
1.144     albertel 2094:     }
1.58      albertel 2095:     if ($removeform) {
                   2096: 	$rendered=~s|<form(.*?)>||g;
                   2097: 	$rendered=~s|</form>||g;
1.374     albertel 2098: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2099:     }
1.144     albertel 2100:     my $companswer;
                   2101:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2102: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2103: 	$companswer=
                   2104: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2105: 						    $env{'request.course.id'},
                   2106: 						    %form);
1.144     albertel 2107:     }
1.58      albertel 2108:     if ($removeform) {
                   2109: 	$companswer=~s|<form(.*?)>||g;
                   2110: 	$companswer=~s|</form>||g;
1.144     albertel 2111: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2112:     }
1.596.2.12.2.  (raeburn 2113:):     my $renderheading = &mt('View of the problem');
                   2114:):     my $answerheading = &mt('Correct answer');
                   2115:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2116:):         my $stu_fullname = $env{'form.fullname'};
                   2117:):         if ($stu_fullname eq '') {
                   2118:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2119:):         }
                   2120:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2121:):         if ($forwhom ne '') {
                   2122:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2123:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2124:):         }
                   2125:):     }
1.468     albertel 2126:     $rendered=
1.588     bisitz   2127:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2128:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2129:        .$rendered
                   2130:        .'</div>';
1.468     albertel 2131:     $companswer=
1.588     bisitz   2132:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2133:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2134:        .$companswer
                   2135:        .'</div>';
1.468     albertel 2136:     my $result;
1.144     albertel 2137:     if ($mode eq 'both') {
1.588     bisitz   2138:         $result=$rendered.$companswer;
1.144     albertel 2139:     } elsif ($mode eq 'text') {
1.588     bisitz   2140:         $result=$rendered;
1.144     albertel 2141:     } elsif ($mode eq 'answer') {
1.588     bisitz   2142:         $result=$companswer;
1.144     albertel 2143:     }
1.71      ng       2144:     return $result;
1.58      albertel 2145: }
1.397     albertel 2146: 
1.396     banghart 2147: sub files_exist {
                   2148:     my ($r, $symb) = @_;
                   2149:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2150:     foreach my $student (@students) {
                   2151:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2152:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2153: 					      $udom,$uname);
1.396     banghart 2154:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2155:         foreach my $submission (@$string) {
                   2156:             my ($partid,$respid) =
                   2157: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2158:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2159: 					   \%record);
                   2160:             return 1 if (@$files);
1.396     banghart 2161:         }
                   2162:     }
1.397     albertel 2163:     return 0;
1.396     banghart 2164: }
1.397     albertel 2165: 
1.394     banghart 2166: sub download_all_link {
                   2167:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2168:0):     unless (&files_exist($r, $symb)) {
                   2169:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2170:0):         return;
                   2171:0):     }
1.395     albertel 2172:     my $all_students = 
                   2173: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2174: 
                   2175:     my $parts =
                   2176: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2177: 
1.394     banghart 2178:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2179:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2180:                              'cgi.'.$identifier.'.symb' => $symb,
                   2181:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2182:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2183: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2184:0):     return;
                   2185:0): }
                   2186:0): 
                   2187:0): sub submit_download_link {
                   2188:0):     my ($request,$symb) = @_;
                   2189:0):     if (!$symb) { return ''; }
                   2190:0):     my $res_error;
                   2191:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2192:0):         &response_type($symb,\$res_error);
                   2193:0):     if ($res_error) {
                   2194:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2195:0):         return;
                   2196:0):     }
                   2197:0):     unless ($numessay) {
                   2198:0):         $request->print(&mt('No essayresponse items found'));
                   2199:0):         return;
                   2200:0):     }
                   2201:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2202:0):     if (@chosenparts) {
                   2203:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2204:0):                                           undef,undef,1));
                   2205:0):     }
                   2206:0):     if ($numessay) {
                   2207:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2208:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2209:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2210:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2211:0):         if (ref($fullname) eq 'HASH') {
                   2212:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2213:0):             if (@students) {
                   2214:0):                 @{$env{'form.stuinfo'}} = @students;
                   2215:0):                 if ($numdropbox) {
                   2216:0):                     &download_all_link($request,$symb);
                   2217:0):                 } else {
                   2218:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2219:0):                 }
                   2220:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2221:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2222:0):             } else {
                   2223:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2224:0):             }
                   2225:0):         } else {
                   2226:0):             $request->print(&mt('Could not retrieve student information'));
                   2227:0):         }
                   2228:0):     } else {
                   2229:0):         $request->print(&mt('No essayresponse items found'));
                   2230:0):     }
                   2231:0):     return;
1.394     banghart 2232: }
1.395     albertel 2233: 
1.432     banghart 2234: sub build_section_inputs {
                   2235:     my $section_inputs;
                   2236:     if ($env{'form.section'} eq '') {
                   2237:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2238:     } else {
                   2239:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2240:         foreach my $section (@sections) {
1.432     banghart 2241:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2242:         }
                   2243:     }
                   2244:     return $section_inputs;
                   2245: }
                   2246: 
1.44      ng       2247: # --------------------------- show submissions of a student, option to grade 
                   2248: sub submission {
1.596.2.12.2.  1(raebur 2249:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2250:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2251:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2252:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2253:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2254:0): 
1.324     albertel 2255:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2256:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          5(raebur 2257:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2258: 
                   2259:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2260:4):         $request->print(
                   2261:4):             '<span class="LC_warning">'.
                   2262:4):             &mt('Unable to view requested student.').
                   2263:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2264:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2265:4):             '</span>');
1.104     albertel 2266: 	return;
                   2267:     }
                   2268: 
1.596.2.12.2.  1(raebur 2269:0):     my $res_error;
                   2270:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2271:0):         &response_type($symb,\$res_error);
                   2272:0):     if ($res_error) {
                   2273:0):         $request->print(&navmap_errormsg());
                   2274:0):         return;
                   2275:0):     }
                   2276:0): 
1.257     albertel 2277:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2278:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2279:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1.596.2.12.2.  1(raebur 2280:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2281:0):         $env{'form.compmsg'} = 1;
                   2282:0):     }
1.257     albertel 2283:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2284:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2285: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2286: 	'/check.gif" height="16" border="0" />';
1.41      ng       2287: 
                   2288:     # header info
                   2289:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2290:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2291:0):         if (@chosenparts) {
                   2292:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2293:0):         } elsif ($divforres) {
                   2294:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2295:0):         } else {
                   2296:0):             $request->print('<br clear="all" />');
                   2297:0):         }
1.41      ng       2298: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2299:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2300:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2301: 
1.44      ng       2302: 	# option to display problem, only once else it cause problems 
                   2303:         # with the form later since the problem has a form.
1.257     albertel 2304: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2305: 	    my $mode;
1.257     albertel 2306: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2307: 		$mode='both';
1.257     albertel 2308: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2309: 		$mode='text';
1.257     albertel 2310: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2311: 		$mode='answer';
                   2312: 	    }
1.329     albertel 2313: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2314: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2315: 	}
1.441     www      2316: 
1.41      ng       2317: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2318:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2319: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2320: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2321: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2322:0): 	}
                   2323:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2324:0): 	# if this subroutine has been called once.
                   2325:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2326: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2327: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2328: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2329: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2330: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2331:0): 	}
                   2332:0): 	if ($env{'form.compmsg'}) {
                   2333:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2334:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2335: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2336: 	}
1.596.2.12.2.  1(raebur 2337:0): 
1.257     albertel 2338: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2339: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2340: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2341: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2342: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2343: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2344: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2345: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2346: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2347: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2348: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2349: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2350: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2351:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2352: 			&build_section_inputs().
1.326     albertel 2353: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2354: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2355: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2356:0): 	if ($env{'form.compmsg'}) {
                   2357:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2358:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2359:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2360:0): 	}
                   2361:0): 	if ($numessay) {
1.257     albertel 2362: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2363: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2364: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2365:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2366: 	}
1.596.2.12.2.  1(raebur 2367:0): 
1.41      ng       2368: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2369: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2370: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2371: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2372: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2373: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2374: 		'" />'."\n".
                   2375: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2376: 	    $cts++;
                   2377: 	}
                   2378: 	$request->print($prnmsg);
1.32      ng       2379: 
1.596.2.12.2.  1(raebur 2380:0): 	if ($numessay) {
1.596.2.4  raeburn  2381: 
                   2382:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2383:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2384:                           keyw => 'Keyword Options',
                   2385:                           list => 'List',
                   2386:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2387:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2388:                      );
1.88      www      2389: #
                   2390: # Print out the keyword options line
                   2391: #
1.596.2.12.2.  1(raebur 2392:0): 	    $request->print(
          8(raebur 2393:4):                 '<div class="LC_columnSection">'
                   2394:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2395:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2396:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2397:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2398:4):  class="page">'.$lt{'past'}.'</a>',
                   2399:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2400:4):                     {legend => $lt{'keyw'}})
                   2401:4):                .'</fieldset></div>'
                   2402:4):             );
                   2403:4): 
1.88      www      2404: #
                   2405: # Load the other essays for similarity check
                   2406: #
1.596.2.12.2.  5(raebur 2407:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2408:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2409:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2410:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2411:9):                 if ($cdom ne '' && $cnum ne '') {
                   2412:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2413:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2414:9):                         my $apath = $1.'_'.$id;
                   2415:9):                         $apath=~s/\W/\_/gs;
                   2416:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2417:9):                     }
                   2418:9):                 }
                   2419:9):             } else {
                   2420:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2421:9): 	        $apath=&escape($apath);
                   2422:9): 	        $apath=~s/\W/\_/gs;
                   2423:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2424:9):             }
1.41      ng       2425:         }
                   2426:     }
1.44      ng       2427: 
1.441     www      2428: # This is where output for one specific student would start
1.592     bisitz   2429:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2430:     $request->print(
                   2431:         "\n\n"
                   2432:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2433:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2434:        ."\n"
                   2435:     );
1.441     www      2436: 
1.592     bisitz   2437:     # Show additional functions if allowed
                   2438:     if ($perm{'vgr'}) {
                   2439:         $request->print(
                   2440:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2441:3):                 'View recent activity',
1.592     bisitz   2442:                 $uname,$udom,'check')
                   2443:            .' '
                   2444:         );
                   2445:     }
                   2446:     if ($perm{'opa'}) {
                   2447:         $request->print(
                   2448:             &Apache::loncommon::pprmlink(
                   2449:                 &mt('Set/Change parameters'),
                   2450:                 $uname,$udom,$symb,'check'));
                   2451:     }
                   2452: 
                   2453:     # Show Problem
1.257     albertel 2454:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2455: 	my $mode;
1.257     albertel 2456: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2457: 	    $mode='both';
1.257     albertel 2458: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2459: 	    $mode='text';
1.257     albertel 2460: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2461: 	    $mode='answer';
                   2462: 	}
1.329     albertel 2463: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2464: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2465:     }
1.144     albertel 2466: 
1.257     albertel 2467:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2468: 
1.44      ng       2469:     # Display student info
1.41      ng       2470:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2471: 
                   2472:     my $result='<div class="LC_Box">'
                   2473:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2474:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2475:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  1(raebur 2476:0):     if ($numresp > $numessay) {
1.588     bisitz   2477:         $result.='<p class="LC_info">'
                   2478:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2479:                 ."</p>\n";
1.469     albertel 2480:     }
                   2481: 
1.596.2.12.2.  1(raebur 2482:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2483:     my $fullname;
                   2484:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2485:0):     if ($numessay) {
1.464     albertel 2486: 	(my $sub_result,$fullname,$col_fullnames)=
                   2487: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2488: 				 $counter);
                   2489: 	$result.=$sub_result;
1.41      ng       2490:     }
1.44      ng       2491:     $request->print($result."\n");
1.588     bisitz   2492: 
1.44      ng       2493:     # print student answer/submission
1.596.2.12.2.  1(raebur 2494:0):     # Options are (1) Last submission only
                   2495:0):     #             (2) Last submission (with detailed information for that submission)
                   2496:0):     #             (3) All transactions (by date)
                   2497:0):     #             (4) The whole record (with detailed information for all transactions)
                   2498:0): 
                   2499:0):     my ($string,$timestamp)= &get_last_submission(\%record);
                   2500:0): 
                   2501:0):     my $lastsubonly;
                   2502:0): 
                   2503:0):     if ($$timestamp eq '') {
                   2504:0):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2505:0):     } else {
                   2506:0):         $lastsubonly =
                   2507:0):             '<div class="LC_grade_submissions_body">'
                   2508:0):            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2509:0): 
                   2510:0): 	my %seenparts;
                   2511:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2512:0): 	foreach my $part (@part_response_id) {
                   2513:0): 	    my ($partid,$respid) = @{ $part };
                   2514:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2515:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2516:0): 		if (exists($seenparts{$partid})) { next; }
                   2517:0): 		$seenparts{$partid}=1;
                   2518:0):                 $request->print(
                   2519:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2520:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2521:0):                                '<a href="javascript:viewSubmitter(\''.
                   2522:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2523:0):                                '\');" target="_self">'.
                   2524:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2525:0):                     '<br />');
                   2526:0): 		next;
                   2527:0): 	    }
                   2528:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2529:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2530:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2531:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2532:0):                     ' <span class="LC_internal_info">'.
                   2533:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2534:0):                     '</span>&nbsp; &nbsp;'.
                   2535:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2536:0): 		next;
                   2537:0): 	    }
                   2538:0): 	    foreach my $submission (@$string) {
                   2539:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2540:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2541:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2542:0): 		# Similarity check
                   2543:0):                 my $similar='';
                   2544:0):                 my ($type,$trial,$rndseed);
                   2545:0):                 if ($hide eq 'rand') {
                   2546:0):                     $type = 'randomizetry';
                   2547:0):                     $trial = $record{"resource.$partid.tries"};
                   2548:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2549:0):                 }
                   2550:0): 		if ($env{'form.checkPlag'}) {
                   2551:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2552:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2553:0): 		    if ($osim) {
                   2554:0): 		        $osim=int($osim*100.0);
                   2555:0):                         if ($hide eq 'anon') {
                   2556:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2557:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2558:0):                         } else {
                   2559:0): 			    $similar='<hr />';
                   2560:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2561:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2562:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2563:0):                                                 $osim,
                   2564:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2565:0):                                             '</span></h3>';
                   2566:0):                             } elsif ($ocrsid ne '') {
                   2567:0):                                 my %old_course_desc;
                   2568:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2569:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2570:9):                                 } else {
          1(raebur 2571:0):                                     my $args;
                   2572:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2573:0):                                         $args = {'one_time' => 1};
                   2574:0):                                     }
                   2575:0):                                     %old_course_desc =
                   2576:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2577:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2578:9):                                 }
          1(raebur 2579:0):                                 $similar .=
                   2580:0):                                     '<h3><span class="LC_warning">'.
                   2581:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2582:0): 				        $osim,
                   2583:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2584:0): 				        $old_course_desc{'description'},
                   2585:0): 				        $old_course_desc{'num'},
                   2586:0): 				        $old_course_desc{'domain'}).
                   2587:0): 				    '</span></h3>';
1.596     raeburn  2588:                             } else {
1.596.2.12.2.  1(raebur 2589:0):                                 $similar .=
                   2590:0):                                     '<h3><span class="LC_warning">'.
                   2591:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2592:0):                                         $osim,
                   2593:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2594:0):                                     '</span></h3>';
1.596     raeburn  2595:                             }
1.596.2.12.2.  1(raebur 2596:0):                             $similar .= '<blockquote><i>'.
                   2597:0):                                         &keywords_highlight($oessay).
                   2598:0):                                         '</i></blockquote><hr />';
                   2599:0): 		        }
                   2600:0):                     }
                   2601:0):                 }
                   2602:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2603:0):                                      undef,$type,$trial,$rndseed);
                   2604:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2605:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2606:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2607:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2608:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2609:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2610:0):                         ' <span class="LC_internal_info">'.
                   2611:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2612:0):                         '</span>&nbsp; &nbsp;';
                   2613:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2614:0): 		    if (@$files) {
1.596.2.2  raeburn  2615:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2616:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2617:                         } else {
1.596.2.12.2.  1(raebur 2618:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2619:0):                                          .'<br /><span class="LC_warning">';
                   2620:0):                             if(@$files == 1) {
                   2621:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2622:0):                             } else {
                   2623:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2624:4):                             }
          1(raebur 2625:0):                             $lastsubonly .= '</span>';
                   2626:0):                             foreach my $file (@$files) {
                   2627:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2628:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2629:4):                             }
1.596     raeburn  2630:                         }
1.596.2.12.2.  1(raebur 2631:0): 			$lastsubonly.='<br />';
1.41      ng       2632: 		    }
1.596.2.12.2.  1(raebur 2633:0):                     if ($hide eq 'anon') {
                   2634:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2635:0):                     } else {
                   2636:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2637:0):                         if ($draft) {
                   2638:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2639:0):                         }
                   2640:0):                         $subval =
                   2641:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2642:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2643:0):                         if ($responsetype eq 'essay') {
                   2644:0):                             $subval =~ s{\n}{<br />}g;
                   2645:0):                         }
                   2646:0):                         $lastsubonly.=$subval."\n";
                   2647:0):                     }
                   2648:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2649:0): 		    $lastsubonly.='</div>';
1.41      ng       2650: 		}
                   2651: 	    }
1.151     albertel 2652: 	}
1.596.2.12.2.  1(raebur 2653:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2654:0):     }
                   2655:0):     $request->print($lastsubonly);
                   2656:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2657:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2658: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2659:3):     }
                   2660:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2661:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2662: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2663: 								 $env{'request.course.id'},
1.44      ng       2664: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2665:5): 								 'Apache::grades::keywords_highlight',
                   2666:5):                                                                  $usec,$identifier));
1.41      ng       2667:     }
1.121     ng       2668:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2669: 	.$udom.'" />'."\n");
1.44      ng       2670:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2671:0):     if (!&canmodify($usec)) {
                   2672:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2673:0):         return;
1.180     albertel 2674:     } else {
1.468     albertel 2675: 	$request->print('</div>'."\n");
1.41      ng       2676:     }
1.33      ng       2677: 
1.596.2.12.2.  1(raebur 2678:0):     # grading message center
                   2679:0): 
                   2680:0):     if ($env{'form.compmsg'}) {
                   2681:0):         my $result='<div class="LC_Box">'.
                   2682:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2683:0):                    '<div class="LC_grade_message_center_body">';
                   2684:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2685:0):         my $msgfor = $givenn.' '.$lastname;
                   2686:0):         if (scalar(@$col_fullnames) > 0) {
                   2687:0):             my $lastone = pop(@$col_fullnames);
                   2688:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2689:0):         }
                   2690:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2691:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2692:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2693:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2694:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2695:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2696:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2697:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2698:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2699:0):                  '<br />&nbsp;('.
                   2700:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2701:0): 	         '</div></div>';
                   2702:0):         $request->print($result);
1.118     ng       2703:     }
1.41      ng       2704: 
                   2705:     my %seen = ();
                   2706:     my @partlist;
1.129     ng       2707:     my @gradePartRespid;
1.375     albertel 2708:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2709:     $request->print(
1.588     bisitz   2710:         '<div class="LC_Box">'
                   2711:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2712:     );
1.592     bisitz   2713:     $request->print(&gradeBox_start());
1.375     albertel 2714:     foreach my $part_response_id (@part_response_id) {
                   2715:     	my ($partid,$respid) = @{ $part_response_id };
                   2716: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2717: 	next if ($seen{$partid} > 0);
1.41      ng       2718: 	$seen{$partid}++;
1.524     raeburn  2719: 	push(@partlist,$partid);
                   2720: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2721: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2722:     }
1.585     bisitz   2723:     $request->print(&gradeBox_end()); # </div>
                   2724:     $request->print('</div>');
1.468     albertel 2725: 
                   2726:     $request->print('<div class="LC_grade_info_links">');
                   2727:     $request->print('</div>');
                   2728: 
1.45      ng       2729:     $result='<input type="hidden" name="partlist'.$counter.
                   2730: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2731:     $result.='<input type="hidden" name="gradePartRespid'.
                   2732: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2733:     my $ctr = 0;
                   2734:     while ($ctr < scalar(@partlist)) {
                   2735: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2736: 	    $partlist[$ctr].'" />'."\n";
                   2737: 	$ctr++;
                   2738:     }
1.468     albertel 2739:     $request->print($result.''."\n");
1.41      ng       2740: 
1.441     www      2741: # Done with printing info for one student
                   2742: 
1.468     albertel 2743:     $request->print('</div>');#LC_grade_show_user
1.441     www      2744: 
                   2745: 
1.41      ng       2746:     # print end of form
                   2747:     if ($counter == $total) {
1.592     bisitz   2748:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2749: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2750: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2751: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2752: 	my $ntstu ='<select name="NTSTU">'.
                   2753: 	    '<option>1</option><option>2</option>'.
                   2754: 	    '<option>3</option><option>5</option>'.
                   2755: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2756: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2757: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2758:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2759: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2760: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2761: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2762: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2763:         $endform.='<span class="LC_warning">'.
                   2764:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2765:                   '</span>'."\n" ;
1.349     albertel 2766:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2767:             "' name='increment' />";
1.485     albertel 2768: 	$endform.='</td></tr></table></form>';
1.41      ng       2769: 	$request->print($endform);
                   2770:     }
                   2771:     return '';
1.38      ng       2772: }
                   2773: 
1.464     albertel 2774: sub check_collaborators {
                   2775:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2776:     my ($result,@col_fullnames);
                   2777:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2778:     foreach my $part (keys(%$handgrade)) {
                   2779: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2780: 					'.maxcollaborators',
                   2781: 					$symb,$udom,$uname);
                   2782: 	next if ($ncol <= 0);
                   2783: 	$part =~ s/\_/\./g;
                   2784: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2785: 	my (@good_collaborators, @bad_collaborators);
                   2786: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2787: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2788: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2789: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2790: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2791: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2792: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2793: 	    # Doing this grep allows 'fuzzy' specification
                   2794: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2795: 			       keys(%$classlist));
                   2796: 	    if (! scalar(@matches)) {
                   2797: 		push(@bad_collaborators, $possible_collaborator);
                   2798: 	    } else {
                   2799: 		push(@good_collaborators, @matches);
                   2800: 	    }
                   2801: 	}
                   2802: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2803: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2804: 	    foreach my $name (@good_collaborators) {
                   2805: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2806: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2807: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2808: 	    }
1.596.2.4  raeburn  2809: 	    $result.='</ol><br />'."\n";
1.466     albertel 2810: 	    my ($part)=split(/\./,$part);
1.464     albertel 2811: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2812: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2813: 		"\n";
                   2814: 	}
                   2815: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2816: 	    $result.='<div class="LC_warning">';
1.464     albertel 2817: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2818: 	    $result .= '</div>';
                   2819: 	}         
                   2820: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2821: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2822: 	    $result .= &mt('This student has submitted too many '.
                   2823: 		'collaborators.  Maximum is [_1].',$ncol);
                   2824: 	    $result .= '</div>';
                   2825: 	}
                   2826:     }
                   2827:     return ($result,$fullname,\@col_fullnames);
                   2828: }
                   2829: 
1.44      ng       2830: #--- Retrieve the last submission for all the parts
1.38      ng       2831: sub get_last_submission {
1.119     ng       2832:     my ($returnhash)=@_;
1.596     raeburn  2833:     my (@string,$timestamp,%lasthidden);
1.119     ng       2834:     if ($$returnhash{'version'}) {
1.46      ng       2835: 	my %lasthash=();
                   2836: 	my ($version);
1.119     ng       2837: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2838: 	    foreach my $key (sort(split(/\:/,
                   2839: 					$$returnhash{$version.':keys'}))) {
                   2840: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2841: 		$timestamp = 
1.545     raeburn  2842: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2843: 	    }
                   2844: 	}
1.596.2.2  raeburn  2845:         my (%typeparts,%randombytry);
1.596     raeburn  2846:         my $showsurv = 
                   2847:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2848:         foreach my $key (sort(keys(%lasthash))) {
                   2849:             if ($key =~ /\.type$/) {
                   2850:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2851:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2852:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2853:                     my ($ign,@parts) = split(/\./,$key);
                   2854:                     pop(@parts);
1.596.2.3  raeburn  2855:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2856:                     if ($lasthash{$key} eq 'randomizetry') {
                   2857:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2858:                     } else {
                   2859:                         unless ($showsurv) {
                   2860:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2861:                         }
1.596     raeburn  2862:                     }
                   2863:                     delete($lasthash{$key});
                   2864:                 }
                   2865:             }
                   2866:         }
                   2867:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2868:         my @randomize = keys(%randombytry);
1.397     albertel 2869: 	foreach my $key (keys(%lasthash)) {
                   2870: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2871:             my $hide;
                   2872:             if (@hidden) {
                   2873:                 foreach my $id (@hidden) {
                   2874:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2875:                         $hide = 'anon';
1.596     raeburn  2876:                         last;
                   2877:                     }
                   2878:                 }
                   2879:             }
1.596.2.2  raeburn  2880:             unless ($hide) {
                   2881:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2882:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2883:                         if ($key =~ /^\Q$id\E/) {
                   2884:                             $hide = 'rand';
                   2885:                             last;
                   2886:                         }
                   2887:                     }
                   2888:                 }
                   2889:             }
1.397     albertel 2890: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2891:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2892:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2893:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2894:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2895: 	}
                   2896:     }
1.397     albertel 2897:     if (!@string) {
                   2898: 	$string[0] =
1.539     riegler  2899: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2900:     }
                   2901:     return (\@string,\$timestamp);
1.38      ng       2902: }
1.35      ng       2903: 
1.44      ng       2904: #--- High light keywords, with style choosen by user.
1.38      ng       2905: sub keywords_highlight {
1.44      ng       2906:     my $string    = shift;
1.257     albertel 2907:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2908:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2909:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2910:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2911:     foreach my $keyword (@keylist) {
                   2912: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2913:     }
                   2914:     return $string;
1.38      ng       2915: }
1.36      ng       2916: 
1.596.2.12.2.  (raeburn 2917:): # For Tasks provide a mechanism to display previous version for one specific student
                   2918:): 
                   2919:): sub show_previous_task_version {
                   2920:):     my ($request,$symb) = @_;
                   2921:):     if ($symb eq '') {
          8(raebur 2922:4):         $request->print(
                   2923:4):             '<span class="LC_error">'.
                   2924:4):             &mt('Unable to handle ambiguous references.').
                   2925:4):             '</span>');
          (raeburn 2926:):         return '';
                   2927:):     }
                   2928:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2929:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2930:):     if (!&canview($usec)) {
          8(raebur 2931:4):         $request->print('<span class="LC_warning">'.
                   2932:4):                         &mt('Unable to view previous version for requested student.').
                   2933:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2934:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2935:4):                         '</span>');
          (raeburn 2936:):         return;
                   2937:):     }
                   2938:):     my $mode = 'both';
                   2939:):     my $isTask = ($symb =~/\.task$/);
                   2940:):     if ($isTask) {
                   2941:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2942:):             if ($env{'form.fullname'} eq '') {
                   2943:):                 $env{'form.fullname'} =
                   2944:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2945:):             }
                   2946:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2947:):             $request->print("\n\n".
                   2948:):                             '<div class="LC_grade_show_user">'.
                   2949:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2950:):                             '</h2>'."\n");
                   2951:):             &Apache::lonxml::clear_problem_counter();
                   2952:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2953:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2954:):             $request->print("\n</div>");
                   2955:):         }
                   2956:):     }
                   2957:):     return;
                   2958:): }
                   2959:): 
                   2960:): sub choose_task_version_form {
                   2961:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2962:):     my $isTask = ($symb =~/\.task$/);
                   2963:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2964:):     if ($isTask) {
                   2965:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2966:):                                               $udom,$uname);
                   2967:):         if (($record{'resource.0.version'} eq '') ||
                   2968:):             ($record{'resource.0.version'} < 2)) {
                   2969:):             return ($record{'resource.0.version'},
                   2970:):                     $record{'resource.0.version'},$result,$js);
                   2971:):         } else {
                   2972:):             $current = $record{'resource.0.version'};
                   2973:):         }
                   2974:):         if ($env{'form.previousversion'}) {
                   2975:):             $displayed = $env{'form.previousversion'};
                   2976:):             $rowtitle = &mt('Choose another version:')
                   2977:):         } else {
                   2978:):             $displayed = $current;
                   2979:):             $rowtitle = &mt('Show earlier version:');
                   2980:):         }
                   2981:):         $result = '<div class="LC_left_float">';
                   2982:):         my $list;
                   2983:):         my $numversions = 0;
                   2984:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2985:):             if ($i == $current) {
                   2986:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2987:):                     next;
                   2988:):                 } else {
                   2989:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2990:):                     $numversions ++;
                   2991:):                 }
                   2992:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2993:):                 unless ($i == $env{'form.previousversion'}) {
                   2994:):                     $numversions ++;
                   2995:):                 }
                   2996:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2997:):             }
                   2998:):         }
                   2999:):         if ($numversions) {
                   3000:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3001:):             $result .=
                   3002:):                 '<form name="getprev" method="post" action=""'.
                   3003:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3004:):                 &Apache::loncommon::start_data_table().
                   3005:):                 &Apache::loncommon::start_data_table_row().
                   3006:):                 '<th align="left">'.$rowtitle.'</th>'.
                   3007:):                 '<td><select name="version">'.
                   3008:):                 '<option>'.&mt('Select').'</option>'.
                   3009:):                 $list.
                   3010:):                 '</select></td>'.
                   3011:):                 &Apache::loncommon::end_data_table_row();
                   3012:):             unless ($nomenu) {
                   3013:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3014:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3015:):                 '<td><span class="LC_nobreak">'.
                   3016:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3017:):                 &mt('Yes').'</label>'.
                   3018:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3019:):                 '</span></td>'.
                   3020:):                 &Apache::loncommon::end_data_table_row();
                   3021:):             }
                   3022:):             $result .=
                   3023:):                 &Apache::loncommon::start_data_table_row().
                   3024:):                 '<th align="left">&nbsp;</th>'.
                   3025:):                 '<td>'.
                   3026:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3027:):                 '</td>'.
                   3028:):                 &Apache::loncommon::end_data_table_row().
                   3029:):                 &Apache::loncommon::end_data_table().
                   3030:):                 '</form>';
                   3031:):             $js = &previous_display_javascript($nomenu,$current);
                   3032:):         } elsif ($displayed && $nomenu) {
                   3033:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3034:):         } else {
                   3035:):             $result .= &mt('No previous versions to show for this student');
                   3036:):         }
                   3037:):         $result .= '</div>';
                   3038:):     }
                   3039:):     return ($current,$displayed,$result,$js);
                   3040:): }
                   3041:): 
                   3042:): sub previous_display_javascript {
                   3043:):     my ($nomenu,$current) = @_;
                   3044:):     my $js = <<"JSONE";
                   3045:): <script type="text/javascript">
                   3046:): // <![CDATA[
                   3047:): function previousVersion(uname,udom,symb) {
                   3048:):     var current = '$current';
                   3049:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3050:):     var prevstr = new RegExp("^\\\\d+\$");
                   3051:):     if (!prevstr.test(version)) {
                   3052:):         return false;
                   3053:):     }
                   3054:):     var url = '';
                   3055:):     if (version == current) {
                   3056:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3057:):     } else {
                   3058:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3059:):     }
                   3060:): JSONE
                   3061:):     if ($nomenu) {
                   3062:):         $js .= <<"JSTWO";
                   3063:):     document.location.href = url;
                   3064:): JSTWO
                   3065:):     } else {
                   3066:):         $js .= <<"JSTHREE";
                   3067:):     var newwin = 0;
                   3068:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3069:):         if (document.getprev.prevwin[i].checked == true) {
                   3070:):             newwin = document.getprev.prevwin[i].value;
                   3071:):         }
                   3072:):     }
                   3073:):     if (newwin == 1) {
                   3074:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3075:):         url = url+'&inhibitmenu=yes';
                   3076:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3077:):             previousWin = window.open(url,'',options,1);
                   3078:):         } else {
                   3079:):             previousWin.location.href = url;
                   3080:):         }
                   3081:):         previousWin.focus();
                   3082:):         return false;
                   3083:):     } else {
                   3084:):         document.location.href = url;
                   3085:):         return false;
                   3086:):     }
                   3087:): JSTHREE
                   3088:):     }
                   3089:):     $js .= <<"ENDJS";
                   3090:):     return false;
                   3091:): }
                   3092:): // ]]>
                   3093:): </script>
                   3094:): ENDJS
                   3095:): 
                   3096:): }
                   3097:): 
1.44      ng       3098: #--- Called from submission routine
1.38      ng       3099: sub processHandGrade {
1.596.2.12.2.  1(raebur 3100:0):     my ($request,$symb) = @_;
1.324     albertel 3101:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3102:     my $button = $env{'form.gradeOpt'};
                   3103:     my $ngrade = $env{'form.NCT'};
                   3104:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3105:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3106:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3107: 
1.44      ng       3108:     if ($button eq 'Save & Next') {
                   3109: 	my $ctr = 0;
                   3110: 	while ($ctr < $ngrade) {
1.257     albertel 3111: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3112:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3113:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3114: 	    if ($errorflag eq 'no_score') {
                   3115: 		$ctr++;
                   3116: 		next;
                   3117: 	    }
1.104     albertel 3118: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3119:4):                 $request->print(
                   3120:4):                     '<span class="LC_error">'
                   3121:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3122:4):                    .'</span>');
1.104     albertel 3123: 		$ctr++;
                   3124: 		next;
                   3125: 	    }
1.596.2.12.2.  1(raebur 3126:5):             if ($numhidden) {
                   3127:5):                 $request->print(
                   3128:5):                     '<span class="LC_info">'
                   3129:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3130:5):                    .'</span><br />');
                   3131:5):             }
1.257     albertel 3132: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3133: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3134: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3135:             my ($feedurl,$showsymb) =
                   3136: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3137: 	    my $messagetail;
1.62      albertel 3138: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3139: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3140: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3141: 		$subject.=' ['.$restitle.']';
1.44      ng       3142: 		my (@msgnum) = split(/,/,$includemsg);
                   3143: 		foreach (@msgnum) {
1.257     albertel 3144: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3145: 		}
1.80      ng       3146: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3147: 		if ($env{'form.withgrades'.$ctr}) {
                   3148: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3149: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3150:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3151: 		}
                   3152: 		$msgstatus = 
                   3153:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3154: 						     $message.$messagetail,
1.418     albertel 3155:                                                      undef,$feedurl,undef,
1.386     raeburn  3156:                                                      undef,undef,$showsymb,
                   3157:                                                      $restitle);
1.574     bisitz   3158: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3159: 				$msgstatus.'<br />');
1.44      ng       3160: 	    }
1.257     albertel 3161: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3162: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3163: 		foreach my $collabstr (@collabstrs) {
                   3164: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3165: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3166: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3167: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3168: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3169: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3170: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3171: 			    next;
1.418     albertel 3172: 			} elsif ($message ne '') {
                   3173: 			    my ($baseurl,$showsymb) = 
                   3174: 				&get_feedurl_and_symb($symb,$collaborator,
                   3175: 						      $udom);
                   3176: 			    if ($env{'form.withgrades'.$ctr}) {
                   3177: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3178:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3179: 			    }
1.418     albertel 3180: 			    $msgstatus = 
                   3181: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3182: 			}
1.44      ng       3183: 		    }
                   3184: 		}
                   3185: 	    }
                   3186: 	    $ctr++;
                   3187: 	}
                   3188:     }
                   3189: 
1.596.2.12.2.  1(raebur 3190:0):     my $res_error;
                   3191:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3192:0):     if ($res_error) {
                   3193:0):         $request->print(&navmap_errormsg());
                   3194:0):         return;
                   3195:0):     }
                   3196:0): 
                   3197:0):     my %keyhash = ();
                   3198:0):     if ($numessay) {
1.119     ng       3199: 	# Keywords sorted in alphabatical order
1.257     albertel 3200: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3201: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
1.596.2.12.2.  2(raebur 3202:0): 	$env{'form.keywords'}           =~ s/^\s+|\s+$//g;
1.257     albertel 3203: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3204: 	$env{'form.keywords'} = join(' ',@keywords);
                   3205: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3206: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3207: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3208: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3209: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3210:0):     }
1.119     ng       3211: 
1.596.2.12.2.  1(raebur 3212:0):     if ($env{'form.compmsg'}) {
1.119     ng       3213: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3214: 	# New messages are saved in env for the next student.
1.119     ng       3215: 	# All messages are saved in nohist_handgrade.db
                   3216: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3217: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3218: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3219: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3220: 		$idx++;
                   3221: 	    }
                   3222: 	    $ctr++;
1.41      ng       3223: 	}
1.119     ng       3224: 	$ctr = 0;
                   3225: 	while ($ctr < $ngrade) {
1.257     albertel 3226: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3227: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3228: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3229: 		$idx++;
                   3230: 	    }
                   3231: 	    $ctr++;
1.41      ng       3232: 	}
1.257     albertel 3233: 	$env{'form.savemsgN'} = --$idx;
                   3234: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3235:0):     }
                   3236:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3237: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3238: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3239:     }
1.596.2.12.2.  1(raebur 3240:0): 
1.44      ng       3241:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3242:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3243:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3244: 	my ($ctr,$total) = (0,0);
                   3245: 	while ($ctr < $ngrade) {
1.257     albertel 3246: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3247: 	    $ctr++;
                   3248: 	}
1.257     albertel 3249: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3250: 	$ctr = 0;
                   3251: 	while ($ctr < $total) {
1.257     albertel 3252: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3253: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3254: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3255:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3256: 	    $ctr++;
                   3257: 	}
                   3258: 	return '';
                   3259:     }
1.36      ng       3260: 
1.44      ng       3261:     # Get the next/previous one or group of students
1.257     albertel 3262:     my $firststu = $env{'form.unamedom0'};
                   3263:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3264:     my $ctr = 2;
1.41      ng       3265:     while ($laststu eq '') {
1.257     albertel 3266: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3267: 	$ctr++;
                   3268: 	$laststu = $firststu if ($ctr > $ngrade);
                   3269:     }
1.44      ng       3270: 
1.41      ng       3271:     my (@parsedlist,@nextlist);
                   3272:     my ($nextflg) = 0;
1.524     raeburn  3273:     foreach my $item (sort 
1.294     albertel 3274: 	     {
                   3275: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3276: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3277: 		 }
                   3278: 		 return $a cmp $b;
                   3279: 	     } (keys(%$fullname))) {
1.41      ng       3280: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3281: 	    push(@parsedlist,$item);
1.41      ng       3282: 	}
1.524     raeburn  3283: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3284: 	if ($button eq 'Previous') {
1.524     raeburn  3285: 	    last if ($item eq $firststu);
                   3286: 	    push(@parsedlist,$item);
1.41      ng       3287: 	}
                   3288:     }
                   3289:     $ctr = 0;
                   3290:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3291:     foreach my $student (@parsedlist) {
1.257     albertel 3292: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3293: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3294: 	
                   3295: 	if ($submitonly eq 'queued') {
                   3296: 	    my %queue_status = 
                   3297: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3298: 							$udom,$uname);
                   3299: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3300: 	}
                   3301: 
1.156     albertel 3302: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3303: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3304: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3305: 	    my $submitted = 0;
1.248     albertel 3306: 	    my $ungraded = 0;
                   3307: 	    my $incorrect = 0;
1.524     raeburn  3308: 	    foreach my $item (keys(%status)) {
                   3309: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3310: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3311: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3312: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3313: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3314: 		    $submitted = 0;
                   3315: 		}
1.41      ng       3316: 	    }
1.156     albertel 3317: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3318: 				     $submitonly eq 'incorrect' ||
                   3319: 				     $submitonly eq 'graded'));
1.248     albertel 3320: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3321: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3322: 	}
1.524     raeburn  3323: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3324: 	last if ($ctr == $ntstu);
1.41      ng       3325: 	$ctr++;
                   3326:     }
1.36      ng       3327: 
1.41      ng       3328:     $ctr = 0;
                   3329:     my $total = scalar(@nextlist)-1;
1.39      ng       3330: 
1.524     raeburn  3331:     foreach (sort(@nextlist)) {
1.41      ng       3332: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3333: 	$env{'form.student'}  = $uname;
                   3334: 	$env{'form.userdom'}  = $udom;
                   3335: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3336:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3337: 	$ctr++;
                   3338:     }
                   3339:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3340:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3341: 	$request->print($the_end);
                   3342:     }
                   3343:     return '';
1.38      ng       3344: }
1.36      ng       3345: 
1.44      ng       3346: #---- Save the score and award for each student, if changed
1.38      ng       3347: sub saveHandGrade {
1.324     albertel 3348:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3349:     my @version_parts;
1.104     albertel 3350:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3351: 					   $env{'request.course.id'});
1.104     albertel 3352:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3353:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3354:     my @parts_graded;
1.77      ng       3355:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3356:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3357:     my %aggregate = ();
                   3358:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3359:5):     if ($env{'form.HIDE'.$newflg}) {
                   3360:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3361:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3362:5):         $totchg += $numchgs;
                   3363:5):     }
1.301     albertel 3364:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3365:     foreach my $new_part (@parts) {
1.337     banghart 3366: 	#collaborator ($submi may vary for different parts
1.259     banghart 3367: 	if ($submitter && $new_part ne $part) { next; }
                   3368: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3369: 	if ($dropMenu eq 'excused') {
1.259     banghart 3370: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3371: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3372: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3373: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3374: 		}
1.364     banghart 3375: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3376: 	    }
1.125     ng       3377: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3378: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3379: 	    foreach my $key (keys(%record)) {
1.259     banghart 3380: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3381: 	    }
1.259     banghart 3382: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3383: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3384:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3385: 
                   3386:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3387: 					       [$new_part]);
                   3388:             my $aggtries =$totaltries;
1.269     raeburn  3389:             if ($last_resets{$new_part}) {
1.270     albertel 3390:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3391: 					   $new_part);
1.269     raeburn  3392:             }
1.270     albertel 3393: 
                   3394:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3395:             if ($aggtries > 0) {
1.327     albertel 3396:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3397:                 $aggregateflag = 1;
                   3398:             }
1.125     ng       3399: 	} elsif ($dropMenu eq '') {
1.259     banghart 3400: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3401: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3402: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3403: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3404: 		next;
                   3405: 	    }
1.259     banghart 3406: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3407: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3408: 	    my $partial= $pts/$wgt;
1.259     banghart 3409: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3410: 		#do not update score for part if not changed.
1.346     banghart 3411:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3412: 		next;
1.251     banghart 3413: 	    } else {
1.524     raeburn  3414: 	        push(@parts_graded,$new_part);
1.153     albertel 3415: 	    }
1.259     banghart 3416: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3417: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3418: 	    }
1.259     banghart 3419: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3420: 	    if ($partial == 0) {
1.153     albertel 3421: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3422: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3423: 		}
1.41      ng       3424: 	    } else {
1.153     albertel 3425: 		if ($record{$reckey} ne 'correct_by_override') {
                   3426: 		    $newrecord{$reckey} = 'correct_by_override';
                   3427: 		}
                   3428: 	    }	    
                   3429: 	    if ($submitter && 
1.259     banghart 3430: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3431: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3432: 	    }
1.259     banghart 3433: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3434: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3435: 	}
1.259     banghart 3436: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3437: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3438: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3439: 	        $dropMenu eq 'reset status')
                   3440: 	   {
1.524     raeburn  3441: 	    push(@version_parts,$new_part);
1.259     banghart 3442: 	}
1.41      ng       3443:     }
1.301     albertel 3444:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3445:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3446: 
1.344     albertel 3447:     if (%newrecord) {
                   3448:         if (@version_parts) {
1.364     banghart 3449:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3450:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3451: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3452: 	    foreach my $new_part (@version_parts) {
                   3453: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3454: 				$new_part,\%newrecord);
                   3455: 	    }
1.259     banghart 3456:         }
1.44      ng       3457: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3458: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3459: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3460: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3461:     }
1.269     raeburn  3462:     if ($aggregateflag) {
                   3463:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3464: 			      $cdom,$cnum);
1.269     raeburn  3465:     }
1.596.2.12.2.  1(raebur 3466:5):     return ('',$pts,$wgt,$totchg);
                   3467:5): }
                   3468:5): 
                   3469:5): sub makehidden {
                   3470:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3471:5):     return unless (ref($record) eq 'HASH');
                   3472:5):     my %modified;
                   3473:5):     my $numchanged = 0;
                   3474:5):     if (exists($record->{$version.':keys'})) {
                   3475:5):         my $partsregexp = $parts;
                   3476:5):         $partsregexp =~ s/,/|/g;
                   3477:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3478:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3479:5):                  my $item = $1;
                   3480:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3481:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3482:5):                  }
                   3483:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3484:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3485:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3486:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3487:5):             }
                   3488:5):         }
                   3489:5):         if (keys(%modified)) {
                   3490:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3491:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3492:5):                 $numchanged ++;
                   3493:5):             }
                   3494:5):         }
                   3495:5):     }
                   3496:5):     return $numchanged;
1.36      ng       3497: }
1.322     albertel 3498: 
1.380     albertel 3499: sub check_and_remove_from_queue {
                   3500:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3501:     my @ungraded_parts;
                   3502:     foreach my $part (@{$parts}) {
                   3503: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3504: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3505: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3506: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3507: 		) {
                   3508: 	    push(@ungraded_parts, $part);
                   3509: 	}
                   3510:     }
                   3511:     if ( !@ungraded_parts ) {
                   3512: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3513: 					       $cnum,$domain,$stuname);
                   3514:     }
                   3515: }
                   3516: 
1.337     banghart 3517: sub handback_files {
                   3518:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3519:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3520:     my $res_error;
                   3521:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3522:     if ($res_error) {
                   3523:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3524:         return;
                   3525:     }
1.596.2.4  raeburn  3526:     my @handedback;
                   3527:     my $file_msg;
1.375     albertel 3528:     my @part_response_id = &flatten_responseType($responseType);
                   3529:     foreach my $part_response_id (@part_response_id) {
                   3530:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3531: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3532:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3533:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3534:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3535: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3536:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3537:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3538:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3539:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3540: 		        &file_name_version_ext($answer_file);
1.355     banghart 3541: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3542:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3543:):                     my ($dir_list,$listerror) =
                   3544:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3545:):                                                  $domain,$stuname,$getpropath);
                   3546:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3547:3):                     # fix filename
1.355     banghart 3548:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3549:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3550:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3551:             	                                $save_file_name);
1.337     banghart 3552:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3553:                         $request->print('<br /><span class="LC_error">'.
                   3554:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3555:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3556:                                         '</span>');
1.356     banghart 3557:                     } else {
1.360     banghart 3558:                         # mark the file as read only
1.596.2.4  raeburn  3559:                         push(@handedback,$save_file_name);
1.367     albertel 3560: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3561: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3562: 			}
                   3563:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3564: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3565: 
1.337     banghart 3566:                     }
1.596.2.12.2.  3(raebur 3567: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 3568:                 }
                   3569:             }
                   3570:         }
1.596.2.4  raeburn  3571:     }
                   3572:     if (@handedback > 0) {
                   3573:         $request->print('<br />');
                   3574:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3575:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3576:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3577:         my ($subject,$message);
                   3578:         if (scalar(@handedback) == 1) {
                   3579:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3580:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3581:         } else {
                   3582:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3583:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3584:         }
                   3585:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3586:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3587:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3588:         my ($feedurl,$showsymb) =
                   3589:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3590:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3591:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3592:         my $msgstatus =
                   3593:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3594:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3595:                  $restitle);
                   3596:         if ($msgstatus) {
                   3597:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3598:         }
                   3599:     }
1.338     banghart 3600:     return;
1.337     banghart 3601: }
                   3602: 
1.418     albertel 3603: sub get_feedurl_and_symb {
                   3604:     my ($symb,$uname,$udom) = @_;
                   3605:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3606:     $url = &Apache::lonnet::clutter($url);
                   3607:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3608: 					$symb,$udom,$uname);
                   3609:     if ($encrypturl =~ /^yes$/i) {
                   3610: 	&Apache::lonenc::encrypted(\$url,1);
                   3611: 	&Apache::lonenc::encrypted(\$symb,1);
                   3612:     }
                   3613:     return ($url,$symb);
                   3614: }
                   3615: 
1.313     banghart 3616: sub get_submitted_files {
                   3617:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3618:     my @files;
                   3619:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3620:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3621:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3622:     	    push(@files,$file_url.$file);
                   3623:         }
                   3624:     }
                   3625:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3626:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3627:     }
                   3628:     return (\@files);
                   3629: }
1.322     albertel 3630: 
1.269     raeburn  3631: # ----------- Provides number of tries since last reset.
                   3632: sub get_num_tries {
                   3633:     my ($record,$last_reset,$part) = @_;
                   3634:     my $timestamp = '';
                   3635:     my $num_tries = 0;
                   3636:     if ($$record{'version'}) {
                   3637:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3638:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3639:                 $timestamp = $$record{$version.':timestamp'};
                   3640:                 if ($timestamp > $last_reset) {
                   3641:                     $num_tries ++;
                   3642:                 } else {
                   3643:                     last;
                   3644:                 }
                   3645:             }
                   3646:         }
                   3647:     }
                   3648:     return $num_tries;
                   3649: }
                   3650: 
                   3651: # ----------- Determine decrements required in aggregate totals 
                   3652: sub decrement_aggs {
                   3653:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3654:     my %decrement = (
                   3655:                         attempts => 0,
                   3656:                         users => 0,
                   3657:                         correct => 0
                   3658:                     );
                   3659:     $decrement{'attempts'} = $aggtries;
                   3660:     if ($solvedstatus =~ /^correct/) {
                   3661:         $decrement{'correct'} = 1;
                   3662:     }
                   3663:     if ($aggtries == $totaltries) {
                   3664:         $decrement{'users'} = 1;
                   3665:     }
1.524     raeburn  3666:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3667:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3668:     }
                   3669:     return;
                   3670: }
                   3671: 
                   3672: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3673: sub get_last_resets {
1.270     albertel 3674:     my ($symb,$courseid,$partids) =@_;
                   3675:     my %last_resets;
1.269     raeburn  3676:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3677:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3678:     my @keys;
                   3679:     foreach my $part (@{$partids}) {
                   3680: 	push(@keys,"$symb\0$part\0resettime");
                   3681:     }
                   3682:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3683: 				     $cdom,$cname);
                   3684:     foreach my $part (@{$partids}) {
                   3685: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3686:     }
1.270     albertel 3687:     return %last_resets;
1.269     raeburn  3688: }
                   3689: 
1.251     banghart 3690: # ----------- Handles creating versions for portfolio files as answers
                   3691: sub version_portfiles {
1.343     banghart 3692:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3693:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3694:     my @returned_keys;
1.255     banghart 3695:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3696:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3697:     foreach my $key (keys(%$record)) {
1.259     banghart 3698:         my $new_portfiles;
1.263     banghart 3699:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3700:             my @versioned_portfiles;
1.367     albertel 3701:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3702:             foreach my $file (@portfiles) {
1.306     banghart 3703:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3704:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3705: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3706: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3707:):                 my $getpropath = 1;
                   3708:):                 my ($dir_list,$listerror) =
                   3709:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3710:):                                              $stu_name,$getpropath);
                   3711:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3712:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3713:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3714:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3715:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3716:                         [$directory.$new_answer],
1.306     banghart 3717:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3718:                 }
1.252     banghart 3719:             }
1.343     banghart 3720:             $$record{$key} = join(',',@versioned_portfiles);
                   3721:             push(@returned_keys,$key);
1.251     banghart 3722:         }
                   3723:     } 
1.343     banghart 3724:     return (@returned_keys);   
1.305     banghart 3725: }
                   3726: 
1.307     banghart 3727: sub get_next_version {
1.341     banghart 3728:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3729:     my $version;
1.596.2.12.2.  (raeburn 3730:):     if (ref($dir_list) eq 'ARRAY') {
                   3731:):         foreach my $row (@{$dir_list}) {
                   3732:):             my ($file) = split(/\&/,$row,2);
                   3733:):             my ($file_name,$file_version,$file_ext) =
                   3734:): 	        &file_name_version_ext($file);
                   3735:):             if (($file_name eq $answer_name) && 
                   3736:): 	        ($file_ext eq $answer_ext)) {
                   3737:):                 # gets here if filename and extension match, 
                   3738:):                 # regardless of version
1.307     banghart 3739:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3740:):                     # a versioned file is found  so save it for later
                   3741:):                     if ($file_version > $version) {
                   3742:): 		        $version = $file_version;
                   3743:):                     }
1.307     banghart 3744: 	        }
                   3745:             }
                   3746:         }
1.596.2.12.2.  (raeburn 3747:):     }
1.307     banghart 3748:     $version ++;
                   3749:     return($version);
                   3750: }
                   3751: 
1.305     banghart 3752: sub version_selected_portfile {
1.306     banghart 3753:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3754:     my ($answer_name,$answer_ver,$answer_ext) =
                   3755:         &file_name_version_ext($file_name);
                   3756:     my $new_answer;
                   3757:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3758:     if($env{'form.copy'} eq '-1') {
                   3759:         $new_answer = 'problem getting file';
                   3760:     } else {
                   3761:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3762:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3763:                             $stu_name,$domain,'copy',
                   3764: 		        '/portfolio'.$directory.$new_answer);
                   3765:     }    
                   3766:     return ($new_answer);
1.251     banghart 3767: }
                   3768: 
1.304     albertel 3769: sub file_name_version_ext {
                   3770:     my ($file)=@_;
                   3771:     my @file_parts = split(/\./, $file);
                   3772:     my ($name,$version,$ext);
                   3773:     if (@file_parts > 1) {
                   3774: 	$ext=pop(@file_parts);
                   3775: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3776: 	    $version=pop(@file_parts);
                   3777: 	}
                   3778: 	$name=join('.',@file_parts);
                   3779:     } else {
                   3780: 	$name=join('.',@file_parts);
                   3781:     }
                   3782:     return($name,$version,$ext);
                   3783: }
                   3784: 
1.44      ng       3785: #--------------------------------------------------------------------------------------
                   3786: #
                   3787: #-------------------------- Next few routines handles grading by section or whole class
                   3788: #
                   3789: #--- Javascript to handle grading by section or whole class
1.42      ng       3790: sub viewgrades_js {
                   3791:     my ($request) = shift;
                   3792: 
1.539     riegler  3793:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3794:6):     &js_escape(\$alertmsg);
          1(raebur 3795:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3796:    function writePoint(partid,weight,point) {
1.125     ng       3797: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3798: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3799: 	if (point == "textval") {
1.125     ng       3800: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3801: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3802: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3803: 		var resetbox = false;
                   3804: 		for (var i=0; i<radioButton.length; i++) {
                   3805: 		    if (radioButton[i].checked) {
                   3806: 			textbox.value = i;
                   3807: 			resetbox = true;
                   3808: 		    }
                   3809: 		}
                   3810: 		if (!resetbox) {
                   3811: 		    textbox.value = "";
                   3812: 		}
                   3813: 		return;
                   3814: 	    }
1.109     matthew  3815: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3816: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3817: 				   ") greater than the weight for the part. Accept?");
                   3818: 		if (resp == false) {
                   3819: 		    textbox.value = "";
                   3820: 		    return;
                   3821: 		}
                   3822: 	    }
1.42      ng       3823: 	    for (var i=0; i<radioButton.length; i++) {
                   3824: 		radioButton[i].checked=false;
1.109     matthew  3825: 		if (parseFloat(point) == i) {
1.42      ng       3826: 		    radioButton[i].checked=true;
                   3827: 		}
                   3828: 	    }
1.41      ng       3829: 
1.42      ng       3830: 	} else {
1.125     ng       3831: 	    textbox.value = parseFloat(point);
1.42      ng       3832: 	}
1.41      ng       3833: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3834: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3835: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3836: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3837: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3838: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3839: 	    if (saveval != "correct") {
                   3840: 		scorename.value = point;
1.43      ng       3841: 		if (selname[0].selected != true) {
                   3842: 		    selname[0].selected = true;
                   3843: 		}
1.42      ng       3844: 	    }
                   3845: 	}
1.125     ng       3846: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3847:     }
                   3848: 
                   3849:     function writeRadText(partid,weight) {
1.125     ng       3850: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3851: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3852:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3853: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3854: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3855: 	    for (var i=0; i<radioButton.length; i++) {
                   3856: 		radioButton[i].checked=false;
                   3857: 
                   3858: 	    }
                   3859: 	    textbox.value = "";
                   3860: 
                   3861: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3862: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3863: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3864: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3865: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3866: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3867: 		if ((saveval != "correct") || override) {
1.42      ng       3868: 		    scorename.value = "";
1.125     ng       3869: 		    if (selval[1].selected) {
                   3870: 			selname[1].selected = true;
                   3871: 		    } else {
                   3872: 			selname[2].selected = true;
                   3873: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3874: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3875: 		    }
1.42      ng       3876: 		}
                   3877: 	    }
1.43      ng       3878: 	} else {
                   3879: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3880: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3881: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3882: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3883: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3884: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3885: 		if ((saveval != "correct") || override) {
1.125     ng       3886: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3887: 		    selname[0].selected = true;
                   3888: 		}
                   3889: 	    }
                   3890: 	}	    
1.42      ng       3891:     }
                   3892: 
                   3893:     function changeSelect(partid,user) {
1.125     ng       3894: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3895: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3896: 	var point  = textbox.value;
1.125     ng       3897: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3898: 
1.109     matthew  3899: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3900: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3901: 	    textbox.value = "";
                   3902: 	    return;
                   3903: 	}
1.109     matthew  3904: 	if (parseFloat(point) > parseFloat(weight)) {
                   3905: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3906: 			       ") greater than the weight of the part. Accept?");
                   3907: 	    if (resp == false) {
                   3908: 		textbox.value = "";
                   3909: 		return;
                   3910: 	    }
                   3911: 	}
1.42      ng       3912: 	selval[0].selected = true;
                   3913:     }
                   3914: 
                   3915:     function changeOneScore(partid,user) {
1.125     ng       3916: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3917: 	if (selval[1].selected || selval[2].selected) {
                   3918: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3919: 	    if (selval[2].selected) {
                   3920: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3921: 	    }
1.269     raeburn  3922:         }
1.42      ng       3923:     }
                   3924: 
                   3925:     function resetEntry(numpart) {
                   3926: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3927: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3928: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3929: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3930: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3931: 	    for (var i=0; i<radioButton.length; i++) {
                   3932: 		radioButton[i].checked=false;
                   3933: 
                   3934: 	    }
                   3935: 	    textbox.value = "";
                   3936: 	    selval[0].selected = true;
                   3937: 
                   3938: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3939: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3940: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3941: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3942: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3943: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3944: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3945: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3946: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3947: 		if (saveselval == "excused") {
1.43      ng       3948: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3949: 		} else {
1.43      ng       3950: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3951: 		}
                   3952: 	    }
1.41      ng       3953: 	}
1.42      ng       3954:     }
                   3955: 
1.41      ng       3956: VIEWJAVASCRIPT
1.42      ng       3957: }
                   3958: 
1.44      ng       3959: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3960: sub viewgrades {
1.596.2.12.2.  1(raebur 3961:0):     my ($request,$symb) = @_;
1.42      ng       3962:     &viewgrades_js($request);
1.41      ng       3963: 
1.168     albertel 3964:     #need to make sure we have the correct data for later EXT calls, 
                   3965:     #thus invalidate the cache
                   3966:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3967:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3968:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3969:     &Apache::lonnet::clear_EXT_cache_status();
                   3970: 
1.398     albertel 3971:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3972: 
                   3973:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3974:     $result.=&jscriptNform($symb);
1.41      ng       3975: 
1.44      ng       3976:     #beginning of class grading form
1.442     banghart 3977:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3978:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3979: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3980: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3981: 	&build_section_inputs().
1.442     banghart 3982: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3983: 
1.596.2.12.2.  7(raebur 3984:6):     #retrieve selected groups
                   3985:6):     my (@groups,$group_display);
          8(raebur 3986:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 3987:6):     if (grep(/^all$/,@groups)) {
                   3988:6):         @groups = ('all');
                   3989:6):     } elsif (grep(/^none$/,@groups)) {
                   3990:6):         @groups = ('none');
                   3991:6):     } elsif (@groups > 0) {
                   3992:6):         $group_display = join(', ',@groups);
                   3993:6):     }
                   3994:6): 
                   3995:6):     my ($common_header,$specific_header,@sections,$section_display);
                   3996:6):     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3997:6):     if (grep(/^all$/,@sections)) {
                   3998:6):         @sections = ('all');
                   3999:6):         if ($group_display) {
                   4000:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   4001:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   4002:6):         } elsif (grep(/^none$/,@groups)) {
                   4003:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   4004:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   4005:6):         } else {
                   4006:6):             $common_header = &mt('Assign Common Grade to Class');
                   4007:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   4008:6):         }
                   4009:6):     } elsif (grep(/^none$/,@sections)) {
                   4010:6):         @sections = ('none');
                   4011:6):         if ($group_display) {
                   4012:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4013:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4014:6):         } elsif (grep(/^none$/,@groups)) {
                   4015:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4016:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4017:6):         } else {
                   4018:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4019:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4020:6):         }
                   4021:6):     } else {
                   4022:6):         $section_display = join (", ",@sections);
                   4023:6):         if ($group_display) {
                   4024:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4025:6):                                  $section_display,$group_display);
                   4026:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4027:6):                                    $section_display,$group_display);
                   4028:6):         } elsif (grep(/^none$/,@groups)) {
                   4029:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4030:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4031:6):         } else {
                   4032:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4033:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4034:6):         }
1.52      albertel 4035:     }
1.596.2.12.2.  7(raebur 4036:6):     my %submit_types = &substatus_options();
                   4037:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4038:6): 
                   4039:6):     if ($env{'form.submitonly'} eq 'all') {
                   4040:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4041:6):     } else {
                   4042:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   4043:6):     }
                   4044:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4045:     #radio buttons/text box for assigning points for a section or class.
                   4046:     #handles different parts of a problem
1.582     raeburn  4047:     my $res_error;
                   4048:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4049:     if ($res_error) {
                   4050:         return &navmap_errormsg();
                   4051:     }
1.42      ng       4052:     my %weight = ();
                   4053:     my $ctsparts = 0;
1.45      ng       4054:     my %seen = ();
1.375     albertel 4055:     my @part_response_id = &flatten_responseType($responseType);
                   4056:     foreach my $part_response_id (@part_response_id) {
                   4057:     	my ($partid,$respid) = @{ $part_response_id };
                   4058: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4059: 	next if $seen{$partid};
                   4060: 	$seen{$partid}++;
1.42      ng       4061: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4062: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4063: 
1.324     albertel 4064: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4065: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4066: 	my $ctr = 0;
1.42      ng       4067: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4068: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4069: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4070: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4071: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4072: 	    $ctr++;
                   4073: 	}
1.485     albertel 4074: 	$radio.='</tr></table>';
                   4075: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4076: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4077: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4078: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4079:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4080:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4081:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4082: 		$weight{$partid}.')"> '.
1.401     albertel 4083: 	    '<option selected="selected"> </option>'.
1.485     albertel 4084: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4085: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4086: 	    '</select></td>'.
                   4087:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4088: 	$line.='<input type="hidden" name="partid_'.
                   4089: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4090: 	$line.='<input type="hidden" name="weight_'.
                   4091: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4092: 
                   4093: 	$result.=
                   4094: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4095: 	    '<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 4096: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4097: 	$ctsparts++;
1.41      ng       4098:     }
1.474     albertel 4099:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4100: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4101:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4102: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4103: 
1.44      ng       4104:     #table listing all the students in a section/class
                   4105:     #header of table
1.596.2.12.2.  7(raebur 4106:6):     if ($env{'form.submitonly'} eq 'all') { 
                   4107:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4108:6):     } else {
                   4109:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   4110:6):     }
                   4111:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4112: 	      &Apache::loncommon::start_data_table_header_row().
                   4113: 	      '<th>'.&mt('No.').'</th>'.
                   4114: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4115:     my $partserror;
                   4116:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4117:     if ($partserror) {
                   4118:         return &navmap_errormsg();
                   4119:     }
1.324     albertel 4120:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4121:     my @partids = ();
1.41      ng       4122:     foreach my $part (@parts) {
                   4123: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  4124:         my $narrowtext = &mt('Tries');
                   4125: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       4126: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 4127: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4128:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4129:0): #
                   4130:0): # FIXME: Looks like $display looks at English text
                   4131:0): #
1.324     albertel 4132: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4133: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4134: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4135:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4136:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4137: 	    next;
1.485     albertel 4138: 	    
1.207     albertel 4139: 	} else {
1.485     albertel 4140: 	    if ($display =~ /Problem Status/) {
                   4141: 		my $grade_status_mt = &mt('Grade Status');
                   4142: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4143: 	    }
                   4144: 	    my $part_mt = &mt('Part:');
                   4145: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4146: 	}
1.485     albertel 4147: 
1.474     albertel 4148: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4149:     }
1.474     albertel 4150:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4151: 
1.270     albertel 4152:     my %last_resets = 
                   4153: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4154: 
1.41      ng       4155:     #get info for each student
1.44      ng       4156:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4157:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4158:     my $ctr = 0;
1.294     albertel 4159:     foreach (sort 
                   4160: 	     {
                   4161: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4162: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4163: 		 }
                   4164: 		 return $a cmp $b;
                   4165: 	     } (keys(%$fullname))) {
1.324     albertel 4166: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 4167:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       4168:     }
1.474     albertel 4169:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4170:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4171:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4172: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4173:6):     if ($ctr == 0) {
1.442     banghart 4174:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4175:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4176:6):                 '<span class="LC_warning">';
                   4177:6):         if ($env{'form.submitonly'} eq 'all') {
                   4178:6):             if (grep(/^all$/,@sections)) {
                   4179:6):                 if (grep(/^all$/,@groups)) {
                   4180:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4181:6):                                    $stu_status);
                   4182:6):                 } elsif (grep(/^none$/,@groups)) {
                   4183:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4184:6):                                    $stu_status);
                   4185:6):                 } else {
                   4186:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4187:6):                                    $group_display,$stu_status);
                   4188:6):                 }
                   4189:6):             } elsif (grep(/^none$/,@sections)) {
                   4190:6):                 if (grep(/^all$/,@groups)) {
                   4191:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4192:6):                                    $stu_status);
                   4193:6):                 } elsif (grep(/^none$/,@groups)) {
                   4194:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4195:6):                                    $stu_status);
                   4196:6):                 } else {
                   4197:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4198:6):                                    $group_display,$stu_status);
                   4199:6):                 }
                   4200:6):             } else {
                   4201:6):                 if (grep(/^all$/,@groups)) {
                   4202:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4203:6):                                    $section_display,$stu_status);
                   4204:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4205:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4206:6):                                    $section_display,$stu_status);
                   4207:6):                 } else {
                   4208:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4209:6):                                    $section_display,$group_display,$stu_status);
                   4210:6):                 }
                   4211:6):             }
                   4212:6):         } else {
                   4213:6):             if (grep(/^all$/,@sections)) {
                   4214:6):                 if (grep(/^all$/,@groups)) {
                   4215:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4216:6):                                    $stu_status,$submission_status);
                   4217:6):                 } elsif (grep(/^none$/,@groups)) {
                   4218:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4219:6):                                    $stu_status,$submission_status);
                   4220:6):                 } else {
                   4221:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4222:6):                                    $group_display,$stu_status,$submission_status);
                   4223:6):                 }
                   4224:6):             } elsif (grep(/^none$/,@sections)) {
                   4225:6):                 if (grep(/^all$/,@groups)) {
                   4226:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4227:6):                                    $stu_status,$submission_status);
                   4228:6):                 } elsif (grep(/^none$/,@groups)) {
                   4229: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.',
                   4230:6):                                    $stu_status,$submission_status);
                   4231:6):                 } else {
                   4232: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.',
                   4233:6):                                    $group_display,$stu_status,$submission_status);
                   4234:6):                 }
                   4235:6):             } else {
                   4236:6):                 if (grep(/^all$/,@groups)) {
                   4237:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4238:6):                                    $section_display,$stu_status,$submission_status);
                   4239:6):                 } elsif (grep(/^none$/,@groups)) {
                   4240: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.',
                   4241:6):                                    $section_display,$stu_status,$submission_status);
                   4242:6):                 } else {
                   4243: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.',
                   4244:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4245:6):                 }
                   4246:6):             }
                   4247:6): 	}
                   4248:6): 	$result .= '</span><br />';
1.96      albertel 4249:     }
1.41      ng       4250:     return $result;
                   4251: }
                   4252: 
1.596.2.12.2.  7(raebur 4253:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4254: sub viewstudentgrade {
1.324     albertel 4255:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4256:     my ($uname,$udom) = split(/:/,$student);
                   4257:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4258:6):     my $submitonly = $env{'form.submitonly'};
                   4259:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4260:6):         my %partstatus = ();
                   4261:6):         if (ref($parts) eq 'ARRAY') {
                   4262:6):             foreach my $apart (@{$parts}) {
                   4263:6):                 my ($part,$type) = &split_part_type($apart);
                   4264:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4265:6):                 $status = 'nothing' if ($status eq '');
                   4266:6):                 $partstatus{$part}      = $status;
                   4267:6):                 my $subkey = "resource.$part.submitted_by";
                   4268:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4269:6):             }
                   4270:6):             my $submitted = 0;
                   4271:6):             my $graded = 0;
                   4272:6):             my $incorrect = 0;
                   4273:6):             foreach my $key (keys(%partstatus)) {
                   4274:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4275:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4276:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4277:6): 
                   4278:6):                 my $partid = (split(/\./,$key))[1];
                   4279:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4280:6):                     $submitted = 0;
                   4281:6):                 }
                   4282:6):             }
                   4283:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4284:6):                                        $submitonly eq 'incorrect' ||
                   4285:6):                                        $submitonly eq 'graded'));
                   4286:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4287:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4288:6):         }
                   4289:6):     }
                   4290:6):     if ($submitonly eq 'queued') {
                   4291:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4292:6):         my %queue_status =
                   4293:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4294:6):                                                     $udom,$uname);
                   4295:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4296:6):     }
                   4297:6):     $$ctr++;
                   4298:6):     my %aggregates = ();
1.474     albertel 4299:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4300:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4301:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4302: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4303: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4304: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4305:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4306:     foreach my $apart (@$parts) {
                   4307: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4308: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4309:         $result.='<td align="center">';
1.269     raeburn  4310:         my ($aggtries,$totaltries);
                   4311:         unless (exists($aggregates{$part})) {
1.270     albertel 4312: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4313: 
                   4314: 	    $aggtries = $totaltries;
1.269     raeburn  4315:             if ($$last_resets{$part}) {  
1.270     albertel 4316:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4317: 					   $part);
                   4318:             }
1.269     raeburn  4319:             $result.='<input type="hidden" name="'.
                   4320:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4321:             $result.='<input type="hidden" name="'.
                   4322:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4323:             $aggregates{$part} = 1;
                   4324:         }
1.41      ng       4325: 	if ($type eq 'awarded') {
1.320     albertel 4326: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4327: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4328: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4329: 	    $result.='<input type="text" name="'.
1.89      albertel 4330: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4331:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4332: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4333: 	} elsif ($type eq 'solved') {
                   4334: 	    my ($status,$foo)=split(/_/,$score,2);
                   4335: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4336: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4337: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4338: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4339: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4340:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4341: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4342: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4343: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4344: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4345: 	} else {
                   4346: 	    $result.='<input type="hidden" name="'.
                   4347: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4348: 		    "\n";
1.233     albertel 4349: 	    $result.='<input type="text" name="'.
1.122     ng       4350: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4351: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4352: 	}
                   4353:     }
1.474     albertel 4354:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4355:     return $result;
1.38      ng       4356: }
                   4357: 
1.44      ng       4358: #--- change scores for all the students in a section/class
                   4359: #    record does not get update if unchanged
1.38      ng       4360: sub editgrades {
1.596.2.12.2.  1(raebur 4361:0):     my ($request,$symb) = @_;
1.41      ng       4362: 
1.433     banghart 4363:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4364:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4365:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4366: 
1.477     albertel 4367:     my $result= &Apache::loncommon::start_data_table().
                   4368: 	&Apache::loncommon::start_data_table_header_row().
                   4369: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4370: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4371:     my %scoreptr = (
                   4372: 		    'correct'  =>'correct_by_override',
                   4373: 		    'incorrect'=>'incorrect_by_override',
                   4374: 		    'excused'  =>'excused',
                   4375: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4376:                     'credited' =>'credit_attempted',
1.43      ng       4377: 		    'nothing'  => '',
                   4378: 		    );
1.257     albertel 4379:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4380: 
1.44      ng       4381:     my (@partid);
                   4382:     my %weight = ();
1.54      albertel 4383:     my %columns = ();
1.44      ng       4384:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4385: 
1.582     raeburn  4386:     my $partserror;
                   4387:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4388:     if ($partserror) {
                   4389:         return &navmap_errormsg();
                   4390:     }
1.54      albertel 4391:     my $header;
1.257     albertel 4392:     while ($ctr < $env{'form.totalparts'}) {
                   4393: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4394: 	push(@partid,$partid);
1.257     albertel 4395: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4396: 	$ctr++;
1.54      albertel 4397:     }
1.324     albertel 4398:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4399:8):     my $totcolspan = 0;
1.54      albertel 4400:     foreach my $partid (@partid) {
1.478     albertel 4401: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4402: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4403: 	$columns{$partid}=2;
                   4404: 	foreach my $stores (@parts) {
                   4405: 	    my ($part,$type) = &split_part_type($stores);
                   4406: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4407: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4408: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4409: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4410:             my $narrowtext = &mt('Tries');
                   4411: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4412: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4413: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4414: 	    $columns{$partid}+=2;
                   4415: 	}
1.596.2.12.2.  2(raebur 4416:8):         $totcolspan += $columns{$partid};
1.54      albertel 4417:     }
                   4418:     foreach my $partid (@partid) {
1.324     albertel 4419: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4420: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4421: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4422: 	    '</th>';
1.54      albertel 4423: 
1.44      ng       4424:     }
1.477     albertel 4425:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4426: 	&Apache::loncommon::start_data_table_header_row().
                   4427: 	$header.
                   4428: 	&Apache::loncommon::end_data_table_header_row();
                   4429:     my @noupdate;
1.126     ng       4430:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4431:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4432: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4433: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4434: 	my %newrecord;
                   4435: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4436:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4437:8):         my $canmodify = &canmodify($usec);
                   4438:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4439:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4440:8):         if (!$canmodify) {
                   4441:8):             push(@noupdate,
                   4442:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4443:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4444:8):             next;
                   4445:8):         }
1.269     raeburn  4446:         my %aggregate = ();
                   4447:         my $aggregateflag = 0;
1.281     albertel 4448: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4449: 	foreach (@partid) {
1.257     albertel 4450: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4451: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4452: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4453: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4454: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4455: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4456: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4457: 	    my $score;
                   4458: 	    if ($partial eq '') {
1.257     albertel 4459: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4460: 	    } elsif ($partial > 0) {
                   4461: 		$score = 'correct_by_override';
                   4462: 	    } elsif ($partial == 0) {
                   4463: 		$score = 'incorrect_by_override';
                   4464: 	    }
1.257     albertel 4465: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4466: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4467: 
1.292     albertel 4468: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4469: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4470: 	    if ($dropMenu eq 'reset status' &&
                   4471: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4472: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4473: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4474: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4475: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4476: 		$updateflag = 1;
1.269     raeburn  4477:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4478:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4479:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4480:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4481:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4482:                     $aggregateflag = 1;
                   4483:                 }
1.139     albertel 4484: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4485: 		$updateflag = 1;
                   4486: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4487: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4488: 		$rec_update++;
1.125     ng       4489: 	    }
                   4490: 
1.93      albertel 4491: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4492: 		'<td align="center">'.$awarded.
                   4493: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4494: 
1.54      albertel 4495: 
                   4496: 	    my $partid=$_;
                   4497: 	    foreach my $stores (@parts) {
                   4498: 		my ($part,$type) = &split_part_type($stores);
                   4499: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4500: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4501: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4502: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4503: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4504: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4505: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4506: 		    $updateflag=1;
                   4507: 		}
1.93      albertel 4508: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4509: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4510: 	    }
1.44      ng       4511: 	}
1.477     albertel 4512: 	$line.="\n";
1.301     albertel 4513: 
                   4514: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4515: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4516: 
1.44      ng       4517: 	if ($updateflag) {
                   4518: 	    $count++;
1.257     albertel 4519: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4520: 				    $udom,$uname);
1.301     albertel 4521: 
                   4522: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4523: 					      $cnum,$udom,$uname)) {
                   4524: 		# need to figure out if should be in queue.
                   4525: 		my %record =  
                   4526: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4527: 					     $udom,$uname);
                   4528: 		my $all_graded = 1;
                   4529: 		my $none_graded = 1;
                   4530: 		foreach my $part (@parts) {
                   4531: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4532: 			$all_graded = 0;
                   4533: 		    } else {
                   4534: 			$none_graded = 0;
                   4535: 		    }
                   4536: 		}
                   4537: 
                   4538: 		if ($all_graded || $none_graded) {
                   4539: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4540: 							   $symb,$cdom,$cnum,
                   4541: 							   $udom,$uname);
                   4542: 		}
                   4543: 	    }
                   4544: 
1.477     albertel 4545: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4546: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4547: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4548: 	    $updateCtr++;
1.93      albertel 4549: 	} else {
1.477     albertel 4550: 	    push(@noupdate,
                   4551: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4552: 	    $noupdateCtr++;
1.44      ng       4553: 	}
1.269     raeburn  4554:         if ($aggregateflag) {
                   4555:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4556: 				  $cdom,$cnum);
1.269     raeburn  4557:         }
1.93      albertel 4558:     }
1.477     albertel 4559:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4560:8):         my $numcols=$totcolspan+2;
1.477     albertel 4561: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4562: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4563: 	    &mt('No Changes Occurred For the Students Below').
                   4564: 	    '</td>'.
1.477     albertel 4565: 	    &Apache::loncommon::end_data_table_row();
                   4566: 	foreach my $line (@noupdate) {
                   4567: 	    $result.=
                   4568: 		&Apache::loncommon::start_data_table_row().
                   4569: 		$line.
                   4570: 		&Apache::loncommon::end_data_table_row();
                   4571: 	}
1.44      ng       4572:     }
1.596.2.12.2.  1(raebur 4573:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4574:     my $msg = '<p><b>'.
                   4575: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4576: 	    $rec_update,$count).'</b><br />'.
                   4577: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4578: 	'</b></p>';
1.44      ng       4579:     return $title.$msg.$result;
1.5       albertel 4580: }
1.54      albertel 4581: 
                   4582: sub split_part_type {
                   4583:     my ($partstr) = @_;
                   4584:     my ($temp,@allparts)=split(/_/,$partstr);
                   4585:     my $type=pop(@allparts);
1.439     albertel 4586:     my $part=join('_',@allparts);
1.54      albertel 4587:     return ($part,$type);
                   4588: }
                   4589: 
1.44      ng       4590: #------------- end of section for handling grading by section/class ---------
                   4591: #
                   4592: #----------------------------------------------------------------------------
                   4593: 
1.5       albertel 4594: 
1.44      ng       4595: #----------------------------------------------------------------------------
                   4596: #
                   4597: #-------------------------- Next few routines handles grading by csv upload
                   4598: #
                   4599: #--- Javascript to handle csv upload
1.27      albertel 4600: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4601:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4602:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4603:6):   &js_escape(\$error1);
                   4604:6):   &js_escape(\$error2);
1.27      albertel 4605:   return(<<ENDPICK);
                   4606:   function verify(vf) {
                   4607:     var foundsomething=0;
                   4608:     var founduname=0;
1.243     albertel 4609:     var foundID=0;
1.27      albertel 4610:     for (i=0;i<=vf.nfields.value;i++) {
                   4611:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4612:       if (i==0 && tw!=0) { foundID=1; }
                   4613:       if (i==1 && tw!=0) { founduname=1; }
                   4614:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4615:     }
1.246     albertel 4616:     if (founduname==0 && foundID==0) {
                   4617: 	alert('$error1');
                   4618: 	return;
1.27      albertel 4619:     }
                   4620:     if (foundsomething==0) {
1.246     albertel 4621: 	alert('$error2');
                   4622: 	return;
1.27      albertel 4623:     }
                   4624:     vf.submit();
                   4625:   }
                   4626:   function flip(vf,tf) {
                   4627:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4628:     var i;
                   4629:     for (i=0;i<=vf.nfields.value;i++) {
                   4630:       //can not pick the same destination field for both name and domain
                   4631:       if (((i ==0)||(i ==1)) && 
                   4632:           ((tf==0)||(tf==1)) && 
                   4633:           (i!=tf) &&
                   4634:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4635:         eval('vf.f'+i+'.selectedIndex=0;')
                   4636:       }
                   4637:     }
                   4638:   }
                   4639: ENDPICK
                   4640: }
                   4641: 
                   4642: sub csvupload_javascript_forward_associate {
1.573     bisitz   4643:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4644:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4645:6):   &js_escape(\$error1);
                   4646:6):   &js_escape(\$error2);
1.27      albertel 4647:   return(<<ENDPICK);
                   4648:   function verify(vf) {
                   4649:     var foundsomething=0;
                   4650:     var founduname=0;
1.243     albertel 4651:     var foundID=0;
1.27      albertel 4652:     for (i=0;i<=vf.nfields.value;i++) {
                   4653:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4654:       if (tw==1) { foundID=1; }
                   4655:       if (tw==2) { founduname=1; }
                   4656:       if (tw>3) { foundsomething=1; }
1.27      albertel 4657:     }
1.246     albertel 4658:     if (founduname==0 && foundID==0) {
                   4659: 	alert('$error1');
                   4660: 	return;
1.27      albertel 4661:     }
                   4662:     if (foundsomething==0) {
1.246     albertel 4663: 	alert('$error2');
                   4664: 	return;
1.27      albertel 4665:     }
                   4666:     vf.submit();
                   4667:   }
                   4668:   function flip(vf,tf) {
                   4669:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4670:     var i;
                   4671:     //can not pick the same destination field twice
                   4672:     for (i=0;i<=vf.nfields.value;i++) {
                   4673:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4674:         eval('vf.f'+i+'.selectedIndex=0;')
                   4675:       }
                   4676:     }
                   4677:   }
                   4678: ENDPICK
                   4679: }
                   4680: 
1.26      albertel 4681: sub csvuploadmap_header {
1.324     albertel 4682:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4683:     my $javascript;
1.257     albertel 4684:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4685: 	$javascript=&csvupload_javascript_reverse_associate();
                   4686:     } else {
                   4687: 	$javascript=&csvupload_javascript_forward_associate();
                   4688:     }
1.45      ng       4689: 
1.257     albertel 4690:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4691:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4692:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4693:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4694:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4695:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4696:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4697:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4698:0): <br />
                   4699:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4700: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4701: <input type="hidden" name="associate"  value="" />
                   4702: <input type="hidden" name="phase"      value="three" />
                   4703: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4704: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4705: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4706: <input type="hidden" name="upfile_associate" 
1.257     albertel 4707:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4708: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4709: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4710: <hr />
                   4711: ENDPICK
1.596.2.12.2.  1(raebur 4712:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4713:     return '';
1.26      albertel 4714: 
                   4715: }
                   4716: 
                   4717: sub csvupload_fields {
1.582     raeburn  4718:     my ($symb,$errorref) = @_;
                   4719:     my (@parts) = &getpartlist($symb,$errorref);
                   4720:     if (ref($errorref)) {
                   4721:         if ($$errorref) {
                   4722:             return;
                   4723:         }
                   4724:     }
                   4725: 
1.556     weissno  4726:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4727: 		['username','Student Username'],
                   4728: 		['domain','Student Domain']);
1.324     albertel 4729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4730:     foreach my $part (sort(@parts)) {
                   4731: 	my @datum;
                   4732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4733: 	my $name=$part;
                   4734: 	if  (!$display) { $display = $name; }
                   4735: 	@datum=($name,$display);
1.244     albertel 4736: 	if ($name=~/^stores_(.*)_awarded/) {
                   4737: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4738: 	}
1.41      ng       4739: 	push(@fields,\@datum);
                   4740:     }
                   4741:     return (@fields);
1.26      albertel 4742: }
                   4743: 
                   4744: sub csvuploadmap_footer {
1.41      ng       4745:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4746:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4747:     $request->print(<<ENDPICK);
1.26      albertel 4748: </table>
                   4749: <input type="hidden" name="nfields" value="$i" />
                   4750: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4751:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4752: </form>
                   4753: ENDPICK
                   4754: }
                   4755: 
1.283     albertel 4756: sub checkforfile_js {
1.539     riegler  4757:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4758:6):     &js_escape(\$alertmsg);
          1(raebur 4759:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4760:     function checkUpload(formname) {
                   4761: 	if (formname.upfile.value == "") {
1.539     riegler  4762: 	    alert("$alertmsg");
1.86      ng       4763: 	    return false;
                   4764: 	}
                   4765: 	formname.submit();
                   4766:     }
                   4767: CSVFORMJS
1.283     albertel 4768:     return $result;
                   4769: }
                   4770: 
                   4771: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4772:0):     my ($request,$symb) = @_;
1.283     albertel 4773:     if (!$symb) {return '';}
                   4774:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4775:0):     $result.=&Apache::loncommon::start_data_table().
                   4776:0):              &Apache::loncommon::start_data_table_header_row().
                   4777:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4778:0):              &Apache::loncommon::end_data_table_header_row().
                   4779:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4780:     my $upload=&mt("Upload Scores");
1.86      ng       4781:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4782:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4783:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4784:     $result.=<<ENDUPFORM;
1.106     albertel 4785: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4786: <input type="hidden" name="symb" value="$symb" />
                   4787: <input type="hidden" name="command" value="csvuploadmap" />
                   4788: $upfile_select
1.589     bisitz   4789: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4790: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4791: </form>
                   4792: ENDUPFORM
1.370     www      4793:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4794:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4795:0):             '</td>'.
                   4796:0):             &Apache::loncommon::end_data_table_row().
                   4797:0):             &Apache::loncommon::end_data_table();
1.86      ng       4798:     return $result;
                   4799: }
                   4800: 
                   4801: 
1.26      albertel 4802: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4803:0):     my ($request,$symb) = @_;
1.41      ng       4804:     if (!$symb) {return '';}
1.72      ng       4805: 
1.41      ng       4806:     my $datatoken;
1.257     albertel 4807:     if (!$env{'form.datatoken'}) {
1.41      ng       4808: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4809:     } else {
1.596.2.12.2.  3(raebur 4810:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4811:8):         if ($datatoken ne '') { 
                   4812:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4813:8):         }
1.26      albertel 4814:     }
1.41      ng       4815:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4816:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4817:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4818:     my ($i,$keyfields);
                   4819:     if (@records) {
1.582     raeburn  4820:         my $fieldserror;
                   4821: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4822:         if ($fieldserror) {
                   4823:             $request->print(&navmap_errormsg());
                   4824:             return;
                   4825:         }
1.257     albertel 4826: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4827: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4828: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4829: 							  \@fields);
                   4830: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4831: 	    chop($keyfields);
                   4832: 	} else {
                   4833: 	    unshift(@fields,['none','']);
                   4834: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4835: 							    \@fields);
1.311     banghart 4836:             foreach my $rec (@records) {
                   4837:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4838:                 if (%temp) {
                   4839:                     $keyfields=join(',',sort(keys(%temp)));
                   4840:                     last;
                   4841:                 }
                   4842:             }
1.41      ng       4843: 	}
                   4844:     }
                   4845:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4846: 
1.41      ng       4847:     return '';
1.27      albertel 4848: }
                   4849: 
1.246     albertel 4850: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 4851:0):     my ($request,$symb)= @_;
                   4852:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 4853:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4854:     my $ignore=&mt('Ignore First Line');
                   4855:     $request->print(<<ENDPICK);
                   4856: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4857: <input type="hidden" name="command"    value="csvuploadassign" />
                   4858: <p>
                   4859: <label>
                   4860:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 4861:0):    $overwrite
1.246     albertel 4862: </label>
                   4863: </p>
                   4864: ENDPICK
                   4865:     my %fields=&get_fields();
                   4866:     if (!defined($fields{'domain'})) {
1.257     albertel 4867: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 4868:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4869:     }
1.257     albertel 4870:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4871: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4872: 	my $cleankey=$1;
                   4873: 	if ($cleankey eq 'command') { next; }
                   4874: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4875: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4876:     }
                   4877:     # FIXME do a check for any duplicated user ids...
                   4878:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4879:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4880: <hr /></form>'."\n");
1.246     albertel 4881:     return '';
                   4882: }
                   4883: 
                   4884: sub get_fields {
                   4885:     my %fields;
1.257     albertel 4886:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4887:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4888: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4889: 	    if ($env{'form.f'.$i} ne 'none') {
                   4890: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4891: 	    }
                   4892: 	} else {
1.257     albertel 4893: 	    if ($env{'form.f'.$i} ne 'none') {
                   4894: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4895: 	    }
                   4896: 	}
1.27      albertel 4897:     }
1.246     albertel 4898:     return %fields;
                   4899: }
                   4900: 
                   4901: sub csvuploadassign {
1.596.2.12.2.  1(raebur 4902:0):     my ($request,$symb) = @_;
1.246     albertel 4903:     if (!$symb) {return '';}
1.345     bowersj2 4904:     my $error_msg = '';
1.596.2.12.2.  3(raebur 4905:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4906:8):     if ($datatoken ne '') {
                   4907:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4908:8):     }
1.246     albertel 4909:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4910:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4911:     my %fields=&get_fields();
1.257     albertel 4912:     my $courseid=$env{'request.course.id'};
1.97      albertel 4913:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4914:     my @notallowed;
1.41      ng       4915:     my @skipped;
1.596.2.4  raeburn  4916:     my @warnings;
1.41      ng       4917:     my $countdone=0;
                   4918:     foreach my $grade (@gradedata) {
                   4919: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4920: 	my $domain;
                   4921: 	if ($entries{$fields{'domain'}}) {
                   4922: 	    $domain=$entries{$fields{'domain'}};
                   4923: 	} else {
1.257     albertel 4924: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4925: 	}
1.243     albertel 4926: 	$domain=~s/\s//g;
1.41      ng       4927: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4928: 	$username=~s/\s//g;
1.243     albertel 4929: 	if (!$username) {
                   4930: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4931: 	    $id=~s/\s//g;
1.243     albertel 4932: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4933: 	    $username=$ids{$id};
                   4934: 	}
1.41      ng       4935: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4936: 	    my $id=$entries{$fields{'ID'}};
                   4937: 	    $id=~s/\s//g;
                   4938: 	    if ($id) {
                   4939: 		push(@skipped,"$id:$domain");
                   4940: 	    } else {
                   4941: 		push(@skipped,"$username:$domain");
                   4942: 	    }
1.41      ng       4943: 	    next;
                   4944: 	}
1.108     albertel 4945: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4946: 	if (!&canmodify($usec)) {
                   4947: 	    push(@notallowed,"$username:$domain");
                   4948: 	    next;
                   4949: 	}
1.244     albertel 4950: 	my %points;
1.41      ng       4951: 	my %grades;
                   4952: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4953: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4954: 		$dest eq 'domain') { next; }
                   4955: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4956: 	    if ($dest=~/stores_(.*)_points/) {
                   4957: 		my $part=$1;
                   4958: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4959: 					      $symb,$domain,$username);
1.345     bowersj2 4960:                 if ($wgt) {
                   4961:                     $entries{$fields{$dest}}=~s/\s//g;
                   4962:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4963:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4964:                                           : 'correct_by_override';
1.596.2.4  raeburn  4965:                     if ($pcr>1) {
                   4966:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4967:                     }
1.345     bowersj2 4968:                     $grades{"resource.$part.awarded"}=$pcr;
                   4969:                     $grades{"resource.$part.solved"}=$award;
                   4970:                     $points{$part}=1;
                   4971:                 } else {
                   4972:                     $error_msg = "<br />" .
                   4973:                         &mt("Some point values were assigned"
                   4974:                             ." for problems with a weight "
                   4975:                             ."of zero. These values were "
                   4976:                             ."ignored.");
                   4977:                 }
1.244     albertel 4978: 	    } else {
                   4979: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4980: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4981: 		my $store_key=$dest;
                   4982: 		$store_key=~s/^stores/resource/;
                   4983: 		$store_key=~s/_/\./g;
                   4984: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4985: 	    }
1.41      ng       4986: 	}
1.596.2.12.2.  1(raebur 4987:0): 	if (! %grades) {
1.508     www      4988:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4989:         } else {
                   4990: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4991: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4992: 					   $env{'request.course.id'},
                   4993: 					   $domain,$username);
1.508     www      4994: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 4995:0): # Successfully stored
1.508     www      4996: 	      $request->print('.');
1.596.2.4  raeburn  4997: # Remove from grading queue
                   4998:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4999:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5000:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5001:                                              $domain,$username);
1.508     www      5002: 	   } else {
                   5003: 	      $request->print("<p><span class=\"LC_error\">".
                   5004:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5005:                                   "$username:$domain",$result)."</span></p>");
                   5006: 	   }
                   5007: 	   $request->rflush();
                   5008: 	   $countdone++;
                   5009:         }
1.41      ng       5010:     }
1.570     www      5011:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5012:     if (@warnings) {
                   5013:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5014:         $request->print(join(', ',@warnings));
                   5015:     }
1.41      ng       5016:     if (@skipped) {
1.571     www      5017: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5018:         $request->print(join(', ',@skipped));
1.106     albertel 5019:     }
                   5020:     if (@notallowed) {
1.571     www      5021: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5022: 	$request->print(join(', ',@notallowed));
1.41      ng       5023:     }
1.106     albertel 5024:     $request->print("<br />\n");
1.345     bowersj2 5025:     return $error_msg;
1.26      albertel 5026: }
1.44      ng       5027: #------------- end of section for handling csv file upload ---------
                   5028: #
                   5029: #-------------------------------------------------------------------
                   5030: #
1.122     ng       5031: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5032: #
                   5033: #--- Select a page/sequence and a student to grade
1.68      ng       5034: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5035:0):     my ($request,$symb) = @_;
1.68      ng       5036: 
1.539     riegler  5037:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5038:6):     &js_escape(\$alertmsg);
          1(raebur 5039:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5040: 
                   5041: function checkPickOne(formname) {
1.76      ng       5042:     if (radioSelection(formname.student) == null) {
1.539     riegler  5043: 	alert("$alertmsg");
1.68      ng       5044: 	return;
                   5045:     }
1.125     ng       5046:     ptr = pullDownSelection(formname.selectpage);
                   5047:     formname.page.value = formname["page"+ptr].value;
                   5048:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5049:     formname.submit();
                   5050: }
                   5051: 
                   5052: LISTJAVASCRIPT
1.118     ng       5053:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5054:0): 
1.257     albertel 5055:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5056:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5057:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5058:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5059: 
1.398     albertel 5060:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5061: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5062: 
1.80      ng       5063:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5064:     my $map_error;
                   5065:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5066:     if ($map_error) {
                   5067:         $request->print(&navmap_errormsg());
                   5068:         return; 
                   5069:     }
1.137     albertel 5070:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5071: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5072: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5073: 
1.596.2.12.2.  1(raebur 5074:0):     # Collection of hidden fields
                   5075:0):     my $ctr=0;
1.70      ng       5076:     foreach (@$titles) {
                   5077: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5078: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5079: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5080: 	$ctr++;
                   5081:     }
1.72      ng       5082:     $result.='<input type="hidden" name="page" />'."\n".
                   5083: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5084: 
1.432     banghart 5085:     $result.=&build_section_inputs();
1.442     banghart 5086:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5087:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5088:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5089:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5090:0): 
                   5091:0):     # Show grading options
                   5092:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5093:0):     my $select = '<select name="selectpage">'."\n";
                   5094:0):     $ctr=0;
                   5095:0):     foreach (@$titles) {
                   5096:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5097:0):         $select.='<option value="'.$ctr.'"'.
                   5098:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5099:0):             '>'.$showtitle.'</option>'."\n";
                   5100:0):         $ctr++;
                   5101:0):     }
                   5102:0):     $select.= '</select>';
1.72      ng       5103: 
1.596.2.12.2.  1(raebur 5104:0):     $result.=
                   5105:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5106:0):        .$select
                   5107:0):        .&Apache::lonhtmlcommon::row_closure();
                   5108:0): 
                   5109:0):     $result.=
                   5110:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5111:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5112:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5113:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5114:0):            .&mt('yes').'</label>'."\n"
                   5115:0):        .&Apache::lonhtmlcommon::row_closure();
                   5116:0): 
                   5117:0):     $result.=
                   5118:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5119:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5120:0):            .&mt('none').' </label>'."\n"
                   5121:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5122:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5123:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5124:0):            .&mt('all submissions with details').' </label>'
                   5125:0):        .&Apache::lonhtmlcommon::row_closure();
                   5126:0): 
                   5127:0):     $result.=
                   5128:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5129:0):        .'<input type="text" name="CODE" value="" />'
                   5130:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5131:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5132: 
1.596.2.12.2.  1(raebur 5133:0):     # Show list of students to select for grading
                   5134:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5135:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5136: 
1.68      ng       5137:     $request->print($result);
                   5138: 
1.485     albertel 5139:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5140: 	&Apache::loncommon::start_data_table().
                   5141: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5142: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5143: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5144: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5145: 	'<th>'.&nameUserString('header').'</th>'.
                   5146: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5147:  
1.596.2.12.2.  8(raebur 5148:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5149:     my $ptr = 1;
1.294     albertel 5150:     foreach my $student (sort 
                   5151: 			 {
                   5152: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5153: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5154: 			     }
                   5155: 			     return $a cmp $b;
                   5156: 			 } (keys(%$fullname))) {
1.68      ng       5157: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5158: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5159:                                   : '</td>');
1.126     ng       5160: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5161: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5162: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5163: 	$studentTable.=
                   5164: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5165:                          : '');
1.68      ng       5166: 	$ptr++;
                   5167:     }
1.484     albertel 5168:     if ($ptr%2 == 0) {
                   5169: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5170: 	    &Apache::loncommon::end_data_table_row();
                   5171:     }
                   5172:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5173:     $studentTable.='<input type="button" '.
1.589     bisitz   5174:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5175: 
                   5176:     $request->print($studentTable);
                   5177: 
                   5178:     return '';
                   5179: }
                   5180: 
                   5181: sub getSymbMap {
1.582     raeburn  5182:     my ($map_error) = @_;
1.132     bowersj2 5183:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5184:     unless (ref($navmap)) {
                   5185:         if (ref($map_error)) {
                   5186:             $$map_error = 'navmap';
                   5187:         }
                   5188:         return;
                   5189:     }
1.68      ng       5190:     my %symbx = ();
                   5191:     my @titles = ();
1.117     bowersj2 5192:     my $minder = 0;
                   5193: 
                   5194:     # Gather every sequence that has problems.
1.240     albertel 5195:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5196: 					       1,0,1);
1.117     bowersj2 5197:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 5198: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 5199: 	    my $title = $minder.'.'.
                   5200: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5201: 	    push(@titles, $title); # minder in case two titles are identical
                   5202: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5203: 	    $minder++;
1.241     albertel 5204: 	}
1.68      ng       5205:     }
                   5206:     return \@titles,\%symbx;
                   5207: }
                   5208: 
1.72      ng       5209: #
                   5210: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5211: sub displayPage {
1.596.2.12.2.  1(raebur 5212:0):     my ($request,$symb) = @_;
1.257     albertel 5213:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5214:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5215:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5216:     my $pageTitle = $env{'form.page'};
1.103     albertel 5217:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5218:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5219:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5220: 
                   5221:     #need to make sure we have the correct data for later EXT calls, 
                   5222:     #thus invalidate the cache
                   5223:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5224:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5225:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5226:     &Apache::lonnet::clear_EXT_cache_status();
                   5227: 
1.103     albertel 5228:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5229:0): 	$request->print(
                   5230:0):             '<span class="LC_warning">'.
                   5231:0):             &mt('Unable to view requested student. ([_1])',
                   5232:0):                 $env{'form.student'}).
                   5233:0):             '</span>');
          8(raebur 5234:4):         return;
1.103     albertel 5235:     }
1.398     albertel 5236:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5237:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5238: 	'</h3>'."\n";
1.500     albertel 5239:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5240:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5241: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5242:     } else {
                   5243: 	delete($env{'form.CODE'});
                   5244:     }
1.71      ng       5245:     &sub_page_js($request);
                   5246:     $request->print($result);
                   5247: 
1.132     bowersj2 5248:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5249:     unless (ref($navmap)) {
                   5250:         $request->print(&navmap_errormsg());
                   5251:         return;
                   5252:     }
1.257     albertel 5253:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5254:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5255:     if (!$map) {
1.485     albertel 5256: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5257: 	return; 
                   5258:     }
1.68      ng       5259:     my $iterator = $navmap->getIterator($map->map_start(),
                   5260: 					$map->map_finish());
                   5261: 
1.71      ng       5262:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5263: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5264: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5265: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5266: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5267: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5268: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5269:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5270: 
1.382     albertel 5271:     if (defined($env{'form.CODE'})) {
                   5272: 	$studentTable.=
                   5273: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5274:     }
1.381     albertel 5275:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5276: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5277: 
1.594     bisitz   5278:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5279:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5280:         '</span>'."\n".
1.484     albertel 5281: 	&Apache::loncommon::start_data_table().
                   5282: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5283:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5284: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5285: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5286: 
1.329     albertel 5287:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5288:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5289:     $iterator->next(); # skip the first BEGIN_MAP
                   5290:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5291:     while ($depth > 0) {
1.68      ng       5292:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5293:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5294: 
1.385     albertel 5295:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5296: 	    my $parts = $curRes->parts();
1.68      ng       5297:             my $title = $curRes->compTitle();
1.71      ng       5298: 	    my $symbx = $curRes->symb();
1.484     albertel 5299: 	    $studentTable.=
                   5300: 		&Apache::loncommon::start_data_table_row().
                   5301: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5302: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5303:2): 		                        : '<br />('.&mt('[_1]parts',
                   5304:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5305: 		 ).
                   5306: 		 '</td>';
1.71      ng       5307: 	    $studentTable.='<td valign="top">';
1.382     albertel 5308: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5309: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5310: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5311: 					     undef,'both',\%form);
1.71      ng       5312: 	    } else {
1.382     albertel 5313: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5314: 		$companswer =~ s|<form(.*?)>||g;
                   5315: 		$companswer =~ s|</form>||g;
1.71      ng       5316: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5317: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5318: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5319: #		}
1.116     ng       5320: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5321: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5322: 	    }
                   5323: 
1.257     albertel 5324: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5325: 
1.257     albertel 5326: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5327: 		if ($record{'version'} eq '') {
1.485     albertel 5328: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5329: 		} else {
1.116     ng       5330: 		    my %responseType = ();
                   5331: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5332: 			my @responseIds =$curRes->responseIds($partid);
                   5333: 			my @responseType =$curRes->responseType($partid);
                   5334: 			my %responseIds;
                   5335: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5336: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5337: 			}
                   5338: 			$responseType{$partid} = \%responseIds;
1.116     ng       5339: 		    }
1.148     albertel 5340: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5341: 
1.71      ng       5342: 		}
1.257     albertel 5343: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5344: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5345:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5346: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5347: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5348:5): 									'','.submission',undef,
                   5349:5):                                                                         $usec,$identifier);
1.71      ng       5350:  
                   5351: 	    }
1.103     albertel 5352: 	    if (&canmodify($usec)) {
1.585     bisitz   5353:             $studentTable.=&gradeBox_start();
1.103     albertel 5354: 		foreach my $partid (@{$parts}) {
                   5355: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5356: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5357: 		    $question++;
                   5358: 		}
1.585     bisitz   5359:             $studentTable.=&gradeBox_end();
1.196     albertel 5360: 		$prob++;
1.71      ng       5361: 	    }
                   5362: 	    $studentTable.='</td></tr>';
1.68      ng       5363: 
1.103     albertel 5364: 	}
1.68      ng       5365:         $curRes = $iterator->next();
                   5366:     }
                   5367: 
1.589     bisitz   5368:     $studentTable.=
                   5369:         '</table>'."\n".
                   5370:         '<input type="button" value="'.&mt('Save').'" '.
                   5371:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5372:         '</form>'."\n";
1.71      ng       5373:     $request->print($studentTable);
                   5374: 
                   5375:     return '';
1.119     ng       5376: }
                   5377: 
                   5378: sub displaySubByDates {
1.148     albertel 5379:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5380:     my $isCODE=0;
1.335     albertel 5381:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5382:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5383:     my $studentTable=&Apache::loncommon::start_data_table().
                   5384: 	&Apache::loncommon::start_data_table_header_row().
                   5385: 	'<th>'.&mt('Date/Time').'</th>'.
                   5386: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5387:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5388: 	'<th>'.&mt('Submission').'</th>'.
                   5389: 	'<th>'.&mt('Status').'</th>'.
                   5390: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5391:     my ($version);
                   5392:     my %mark;
1.148     albertel 5393:     my %orders;
1.119     ng       5394:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5395:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5396: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5397:     }
1.335     albertel 5398: 
                   5399:     my $interaction;
1.525     raeburn  5400:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5401:5):     my (%lastrndseed,%lasttype);
1.119     ng       5402:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5403: 	my $timestamp = 
                   5404: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5405: 	if (exists($$record{$version.':resource.0.version'})) {
                   5406: 	    $interaction = $$record{$version.':resource.0.version'};
                   5407: 	}
1.596.2.12.2.  (raeburn 5408:):         if ($isTask && $env{'form.previousversion'}) {
                   5409:):             next unless ($interaction == $env{'form.previousversion'});
                   5410:):         }
1.335     albertel 5411: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5412: 		             : "$version:resource");
1.467     albertel 5413: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5414: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5415: 	if ($isCODE) {
                   5416: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5417: 	}
1.596.2.12.2.  (raeburn 5418:):         if ($isTask) {
                   5419:):             $studentTable.='<td>'.$interaction.'</td>';
                   5420:):         }
1.119     ng       5421: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5422: 	my @displaySub = ();
                   5423: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5424:             my ($hidden,$type);
                   5425:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5426:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5427:                 $hidden = 1;
                   5428:             }
1.596.2.12.2.  1(raebur 5429:0): 	    my @matchKey;
                   5430:0):             if ($isTask) {
                   5431:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
                   5432:0):             } else {
                   5433:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5434:0):             }
1.122     ng       5435: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5436: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5437: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5438: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5439: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5440:                     
1.335     albertel 5441: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5442: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5443:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5444:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5445:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5446:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5447:                                    .'</span>'
                   5448:                                    .' <b>';
1.596     raeburn  5449:                     if ($hidden) {
                   5450:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5451:                     } else {
1.596.2.2  raeburn  5452:                         my ($trial,$rndseed,$newvariation);
                   5453:                         if ($type eq 'randomizetry') {
                   5454:                             $trial = $$record{"$where.$partid.tries"};
                   5455:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5456:                         }
1.596     raeburn  5457: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5458: 			    $displaySub[0].=&mt('Trial not counted');
                   5459: 		        } else {
                   5460: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5461: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5462:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5463:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5464:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5465:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5466:                                 }
                   5467:                             }
1.596.2.12.2.  4(raebur 5468:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5469:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5470: 		        }
                   5471: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5472:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5473: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5474: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5475: 			    $orders{$partid}->{$responseId}=
                   5476: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5477:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5478: 		        }
1.596.2.2  raeburn  5479: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5480: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5481: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5482:                     }
1.147     albertel 5483: 		}
                   5484: 	    }
1.335     albertel 5485: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5486: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5487: 				    $$record{"$where.$partid.checkedin"},
                   5488: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5489: 					'<br />';
1.335     albertel 5490: 	    }
                   5491: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5492: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5493: 		    lc($$record{"$where.$partid.award"}).' '.
                   5494: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5495: 		    '<br />';
                   5496: 	    }
1.335     albertel 5497: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5498: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5499: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5500: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5501: 		$displaySub[2].=
                   5502: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5503: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5504: 	    }
                   5505: 	}
                   5506: 	# needed because old essay regrader has not parts info
                   5507: 	if (exists $$record{"$version:resource.regrader"}) {
                   5508: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5509: 	}
                   5510: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5511: 	if ($displaySub[2]) {
1.467     albertel 5512: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5513: 	}
1.467     albertel 5514: 	$studentTable.='&nbsp;</td>'.
                   5515: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5516:     }
1.467     albertel 5517:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5518:     return $studentTable;
1.71      ng       5519: }
                   5520: 
                   5521: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5522:0):     my ($request,$symb) = @_;
1.71      ng       5523: 
1.257     albertel 5524:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5525:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5526:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5527:     my $pageTitle = $env{'form.page'};
1.103     albertel 5528:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5529:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5530:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5531:     if (!&canmodify($usec)) {
1.526     raeburn  5532: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5533: 	return;
                   5534:     }
1.398     albertel 5535:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5536:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5537: 	'</h3>'."\n";
1.70      ng       5538: 
1.68      ng       5539:     $request->print($result);
                   5540: 
1.582     raeburn  5541: 
1.132     bowersj2 5542:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5543:     unless (ref($navmap)) {
                   5544:         $request->print(&navmap_errormsg());
                   5545:         return;
                   5546:     }
1.257     albertel 5547:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5548:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5549:     if (!$map) {
1.527     raeburn  5550: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5551: 	return; 
                   5552:     }
1.71      ng       5553:     my $iterator = $navmap->getIterator($map->map_start(),
                   5554: 					$map->map_finish());
1.70      ng       5555: 
1.484     albertel 5556:     my $studentTable=
                   5557: 	&Apache::loncommon::start_data_table().
                   5558: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5559: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5560: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5561: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5562: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5563: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5564: 
                   5565:     $iterator->next(); # skip the first BEGIN_MAP
                   5566:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5567:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5568:     while ($depth > 0) {
1.71      ng       5569:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5570:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5571: 
1.385     albertel 5572:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5573: 	    my $parts = $curRes->parts();
1.71      ng       5574:             my $title = $curRes->compTitle();
                   5575: 	    my $symbx = $curRes->symb();
1.484     albertel 5576: 	    $studentTable.=
                   5577: 		&Apache::loncommon::start_data_table_row().
                   5578: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5579: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5580:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5581: 		.')').'</td>';
1.71      ng       5582: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5583: 
                   5584: 	    my %newrecord=();
                   5585: 	    my @displayPts=();
1.269     raeburn  5586:             my %aggregate = ();
                   5587:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5588:5):             if ($env{'form.HIDE'.$prob}) {
                   5589:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5590:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5591:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5592:5):                 $hideflag += $numchgs;
                   5593:5):             }
1.71      ng       5594: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5595: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5596: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5597: 
1.257     albertel 5598: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5599: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5600: 		my $partial = $newpts/$wgt;
                   5601: 		my $score;
                   5602: 		if ($partial > 0) {
                   5603: 		    $score = 'correct_by_override';
1.125     ng       5604: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5605: 		    $score = 'incorrect_by_override';
                   5606: 		}
1.257     albertel 5607: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5608: 		if ($dropMenu eq 'excused') {
1.71      ng       5609: 		    $partial = '';
                   5610: 		    $score = 'excused';
1.125     ng       5611: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5612: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5613: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5614: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5615: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5616: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5617: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5618: 		    $changeflag++;
                   5619: 		    $newpts = '';
1.269     raeburn  5620:                     
                   5621:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5622:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5623:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5624:                     if ($aggtries > 0) {
                   5625:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5626:                         $aggregateflag = 1;
                   5627:                     }
1.71      ng       5628: 		}
1.324     albertel 5629: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5630: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5631: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5632: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5633: 		    '&nbsp;<br />';
1.526     raeburn  5634: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5635: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5636: 		    '&nbsp;<br />';
1.71      ng       5637: 		$question++;
1.380     albertel 5638: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5639: 
1.71      ng       5640: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5641: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5642: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5643: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5644: 
                   5645: 		$changeflag++;
                   5646: 	    }
                   5647: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5648: 		my %record = 
                   5649: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5650: 					     $udom,$uname);
                   5651: 
                   5652: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5653: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5654: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5655: 		    $newrecord{'resource.CODE'} = '';
                   5656: 		}
1.257     albertel 5657: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5658: 					$udom,$uname);
1.382     albertel 5659: 		%record = &Apache::lonnet::restore($symbx,
                   5660: 						   $env{'request.course.id'},
                   5661: 						   $udom,$uname);
1.380     albertel 5662: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5663: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5664: 	    }
1.380     albertel 5665: 	    
1.269     raeburn  5666:             if ($aggregateflag) {
                   5667:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5668:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5669:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5670:             }
1.125     ng       5671: 
1.71      ng       5672: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5673: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5674: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5675: 
1.196     albertel 5676: 	    $prob++;
1.68      ng       5677: 	}
1.71      ng       5678:         $curRes = $iterator->next();
1.68      ng       5679:     }
1.98      albertel 5680: 
1.484     albertel 5681:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5682:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5683: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5684:5): 		  $changeflag).'<br />');
                   5685:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5686:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5687:5):                      $hideflag).'<br />');
                   5688:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5689: 
1.70      ng       5690:     return '';
                   5691: }
                   5692: 
1.72      ng       5693: #-------- end of section for handling grading by page/sequence ---------
                   5694: #
                   5695: #-------------------------------------------------------------------
                   5696: 
1.581     www      5697: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5698: #
                   5699: #------ start of section for handling grading by page/sequence ---------
                   5700: 
1.423     albertel 5701: =pod
                   5702: 
                   5703: =head1 Bubble sheet grading routines
                   5704: 
1.424     albertel 5705:   For this documentation:
                   5706: 
                   5707:    'scanline' refers to the full line of characters
                   5708:    from the file that we are parsing that represents one entire sheet
                   5709: 
                   5710:    'bubble line' refers to the data
1.596.2.6  raeburn  5711:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5712: 
                   5713: 
1.596.2.6  raeburn  5714: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5715: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5716: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5717: one of the predefined configurations for what each scanline looks
                   5718: like.
                   5719: 
                   5720: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5721: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5722: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5723:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5724: invalid student/employee ID
1.424     albertel 5725: 
                   5726: If the CODE option is used that determines the randomization of the
1.556     weissno  5727: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5728: username:domain.
                   5729: 
                   5730: During the validation phase the instructor can choose to skip scanlines. 
                   5731: 
1.596.2.6  raeburn  5732: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5733: 
                   5734:   scantron_original_filename (unmodified original file)
                   5735:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5736:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5737: 
                   5738: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5739: correction information that isn't representable in the bubblesheet
1.424     albertel 5740: file (see &scantron_getfile() for more information)
                   5741: 
                   5742: After all scanlines are either valid, marked as valid or skipped, then
                   5743: foreach line foreach problem in the picked sequence, an ssi request is
                   5744: made that simulates a user submitting their selected letter(s) against
                   5745: the homework problem.
1.423     albertel 5746: 
                   5747: =over 4
                   5748: 
                   5749: 
                   5750: 
                   5751: =item defaultFormData
                   5752: 
                   5753:   Returns html hidden inputs used to hold context/default values.
                   5754: 
                   5755:  Arguments:
                   5756:   $symb - $symb of the current resource 
                   5757: 
                   5758: =cut
1.422     foxr     5759: 
1.81      albertel 5760: sub defaultFormData {
1.324     albertel 5761:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 5762:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5763: }
                   5764: 
1.447     foxr     5765: 
1.423     albertel 5766: =pod 
                   5767: 
                   5768: =item getSequenceDropDown
                   5769: 
                   5770:    Return html dropdown of possible sequences to grade
                   5771:  
                   5772:  Arguments:
1.582     raeburn  5773:    $symb - $symb of the current resource
                   5774:    $map_error - ref to scalar which will container error if
                   5775:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5776: 
                   5777: =cut
1.422     foxr     5778: 
1.75      albertel 5779: sub getSequenceDropDown {
1.582     raeburn  5780:     my ($symb,$map_error)=@_;
1.75      albertel 5781:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5782:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5783:     if (ref($map_error)) {
                   5784:         return if ($$map_error);
                   5785:     }
1.137     albertel 5786:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5787:     my $ctr=0;
                   5788:     foreach (@$titles) {
                   5789: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5790: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5791: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5792: 	    '>'.$showtitle.'</option>'."\n";
                   5793: 	$ctr++;
                   5794:     }
                   5795:     $result.= '</select>';
                   5796:     return $result;
                   5797: }
                   5798: 
1.495     albertel 5799: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5800:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5801: 
                   5802: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5803: 
1.509     raeburn  5804: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5805:                                    # matchresponse or rankresponse, where 
                   5806:                                    # an individual response can have multiple 
                   5807:                                    # lines
1.503     raeburn  5808: 
                   5809: my %responsetype_per_response;     # responsetype for each response
                   5810: 
1.596.2.12.2.  6(raebur 5811:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5812:3):                                    # numbered response. Needed when randomorder
                   5813:3):                                    # or randompick are in use. Key is ID, value 
                   5814:3):                                    # is response number.
                   5815:3): 
1.495     albertel 5816: # Save and restore the bubble lines array to the form env.
                   5817: 
                   5818: 
                   5819: sub save_bubble_lines {
                   5820:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5821: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5822: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5823: 	    $first_bubble_line{$line};
1.503     raeburn  5824:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5825:             $subdivided_bubble_lines{$line};
                   5826:         $env{"form.scantron.responsetype.$line"} =
                   5827:             $responsetype_per_response{$line};
1.495     albertel 5828:     }
1.596.2.12.2.  6(raebur 5829:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5830:3):         my $line = $masterseq_id_responsenum{$resid};
                   5831:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5832:3):     }
1.495     albertel 5833: }
                   5834: 
                   5835: 
                   5836: sub restore_bubble_lines {
                   5837:     my $line = 0;
                   5838:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5839:3):     %masterseq_id_responsenum = ();
1.495     albertel 5840:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5841: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5842: 	$bubble_lines_per_response{$line} = $value;
                   5843: 	$first_bubble_line{$line}  =
                   5844: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5845:         $subdivided_bubble_lines{$line} =
                   5846:             $env{"form.scantron.sub_bubblelines.$line"};
                   5847:         $responsetype_per_response{$line} =
                   5848:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5849:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5850:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5851: 	$line++;
                   5852:     }
                   5853: }
                   5854: 
1.423     albertel 5855: =pod 
                   5856: 
                   5857: =item scantron_filenames
                   5858: 
                   5859:    Returns a list of the scantron files in the current course 
                   5860: 
                   5861: =cut
1.422     foxr     5862: 
1.202     albertel 5863: sub scantron_filenames {
1.257     albertel 5864:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5865:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5866:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5867:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5868:):                                                         $cname,$getpropath);
1.202     albertel 5869:     my @possiblenames;
1.596.2.12.2.  (raeburn 5870:):     if (ref($dirlist) eq 'ARRAY') {
                   5871:):         foreach my $filename (sort(@{$dirlist})) {
                   5872:): 	    ($filename)=split(/&/,$filename);
                   5873:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5874:): 	    $filename=~s/^scantron_orig_//;
                   5875:): 	    push(@possiblenames,$filename);
                   5876:):         }
1.202     albertel 5877:     }
                   5878:     return @possiblenames;
                   5879: }
                   5880: 
1.423     albertel 5881: =pod 
                   5882: 
                   5883: =item scantron_uploads
                   5884: 
                   5885:    Returns  html drop-down list of scantron files in current course.
                   5886: 
                   5887:  Arguments:
                   5888:    $file2grade - filename to set as selected in the dropdown
                   5889: 
                   5890: =cut
1.422     foxr     5891: 
1.202     albertel 5892: sub scantron_uploads {
1.209     ng       5893:     my ($file2grade) = @_;
1.202     albertel 5894:     my $result=	'<select name="scantron_selectfile">';
                   5895:     $result.="<option></option>";
                   5896:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5897: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5898:     }
                   5899:     $result.="</select>";
                   5900:     return $result;
                   5901: }
                   5902: 
1.423     albertel 5903: =pod 
                   5904: 
                   5905: =item scantron_scantab
                   5906: 
                   5907:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5908:   file.
                   5909: 
                   5910: =cut
1.422     foxr     5911: 
1.82      albertel 5912: sub scantron_scantab {
                   5913:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5914:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 5915:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5916:     if (@lines > 0) {
                   5917:         foreach my $line (@lines) {
                   5918:             next if (($line =~ /^\#/) || ($line eq ''));
                   5919: 	    my ($name,$descrip)=split(/:/,$line);
                   5920: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5921:         }
1.82      albertel 5922:     }
                   5923:     $result.='</select>'."\n";
1.518     raeburn  5924:     return $result;
                   5925: }
                   5926: 
1.423     albertel 5927: =pod 
                   5928: 
                   5929: =item scantron_CODElist
                   5930: 
                   5931:   Returns html drop down of the saved CODE lists from current course,
                   5932:   generated from earlier printings.
                   5933: 
                   5934: =cut
1.422     foxr     5935: 
1.186     albertel 5936: sub scantron_CODElist {
1.257     albertel 5937:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5938:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5939:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5940:     my $namechoice='<option></option>';
1.225     albertel 5941:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5942: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5943: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5944: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5945:     }
                   5946:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5947:     return $namechoice;
                   5948: }
                   5949: 
1.423     albertel 5950: =pod 
                   5951: 
                   5952: =item scantron_CODEunique
                   5953: 
                   5954:   Returns the html for "Each CODE to be used once" radio.
                   5955: 
                   5956: =cut
1.422     foxr     5957: 
1.186     albertel 5958: sub scantron_CODEunique {
1.532     bisitz   5959:     my $result='<span class="LC_nobreak">
1.272     albertel 5960:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5961:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5962:                 </span>
1.532     bisitz   5963:                 <span class="LC_nobreak">
1.272     albertel 5964:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5965:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5966:                 </span>';
1.186     albertel 5967:     return $result;
                   5968: }
1.423     albertel 5969: 
                   5970: =pod 
                   5971: 
                   5972: =item scantron_selectphase
                   5973: 
1.596.2.6  raeburn  5974:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5975:   Allows for - starting a grading run.
1.424     albertel 5976:              - downloading existing scan data (original, corrected
1.423     albertel 5977:                                                 or skipped info)
                   5978: 
                   5979:              - uploading new scan data
                   5980: 
                   5981:  Arguments:
                   5982:   $r          - The Apache request object
                   5983:   $file2grade - name of the file that contain the scanned data to score
                   5984: 
                   5985: =cut
1.186     albertel 5986: 
1.75      albertel 5987: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 5988:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5989:     if (!$symb) {return '';}
1.582     raeburn  5990:     my $map_error;
                   5991:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5992:     if ($map_error) {
                   5993:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5994:         return;
                   5995:     }
1.324     albertel 5996:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5997:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5998:     my $format_selector=&scantron_scantab();
1.186     albertel 5999:     my $CODE_selector=&scantron_CODElist();
                   6000:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6001:     my $result;
1.422     foxr     6002: 
1.513     foxr     6003:     $ssi_error = 0;
                   6004: 
1.596.2.4  raeburn  6005:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   6006:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   6007: 
                   6008:         # Chunk of form to prompt for a scantron file upload.
                   6009: 
                   6010:         $r->print('
1.596.2.12.2.  9(raebur 6011:9):     <br />');
                   6012:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6013:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6014:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6015:9):         &js_escape(\$alertmsg);
                   6016:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6017:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6018:     function checkUpload(formname) {
                   6019:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6020:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6021:             return false;
                   6022:         }
                   6023:         formname.submit();
1.596.2.12.2.  9(raebur 6024:9):     }'."\n".$formatjs));
                   6025:9):         $r->print('
1.596.2.4  raeburn  6026:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6027:                 '.$default_form_data.'
                   6028:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6029:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6030:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6031:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6032:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6033:9):                 <th>
                   6034:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6035:9):                 </th>
                   6036:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6037:9):               '.&Apache::loncommon::start_data_table_row().'
                   6038:9):             <td>
                   6039:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6040:9):         if ($formatoptions) {
                   6041:9):             $r->print('</td>
                   6042:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6043:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6044:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6045:9):                  </td>
                   6046:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6047:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6048:9):                  <td>'
                   6049:9):             );
                   6050:9):         } else {
                   6051:9):             $r->print(' <br />');
                   6052:9):         }
                   6053:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6054:9):               </td>
                   6055:9):              '.&Apache::loncommon::end_data_table_row().'
                   6056:9):              '.&Apache::loncommon::end_data_table().'
                   6057:9):              </form>'
                   6058:9):         );
1.596.2.4  raeburn  6059: 
                   6060:     }
                   6061: 
1.422     foxr     6062:     # Chunk of form to prompt for a file to grade and how:
                   6063: 
1.489     albertel 6064:     $result.= '
                   6065:     <br />
                   6066:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6067:     <input type="hidden" name="command" value="scantron_warning" />
                   6068:     '.$default_form_data.'
                   6069:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6070:        '.&Apache::loncommon::start_data_table_header_row().'
                   6071:             <th colspan="2">
1.492     albertel 6072:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6073:             </th>
                   6074:        '.&Apache::loncommon::end_data_table_header_row().'
                   6075:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6076:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6077:        '.&Apache::loncommon::end_data_table_row().'
                   6078:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6079:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6080:        '.&Apache::loncommon::end_data_table_row().'
                   6081:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6082:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6083:        '.&Apache::loncommon::end_data_table_row().'
                   6084:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6085:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6086:        '.&Apache::loncommon::end_data_table_row().'
                   6087:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6088:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6089:        '.&Apache::loncommon::end_data_table_row().'
                   6090:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6091: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6092:             <td>
1.492     albertel 6093: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6094:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6095:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6096: 	    </td>
1.489     albertel 6097:        '.&Apache::loncommon::end_data_table_row().'
                   6098:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6099:             <td colspan="2">
1.572     www      6100:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6101:             </td>
1.489     albertel 6102:        '.&Apache::loncommon::end_data_table_row().'
                   6103:     '.&Apache::loncommon::end_data_table().'
                   6104:     </form>
                   6105: ';
1.162     albertel 6106:    
                   6107:     $r->print($result);
                   6108: 
1.422     foxr     6109:     # Chunk of the form that prompts to view a scoring office file,
                   6110:     # corrected file, skipped records in a file.
                   6111: 
1.489     albertel 6112:     $r->print('
                   6113:    <br />
                   6114:    <form action="/adm/grades" name="scantron_download">
                   6115:      '.$default_form_data.'
                   6116:      <input type="hidden" name="command" value="scantron_download" />
                   6117:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6118:        '.&Apache::loncommon::start_data_table_header_row().'
                   6119:               <th>
1.492     albertel 6120:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6121:               </th>
                   6122:        '.&Apache::loncommon::end_data_table_header_row().'
                   6123:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6124:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6125:                 <br />
1.492     albertel 6126:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6127:        '.&Apache::loncommon::end_data_table_row().'
                   6128:      '.&Apache::loncommon::end_data_table().'
                   6129:    </form>
                   6130:    <br />
                   6131: ');
1.162     albertel 6132: 
1.457     banghart 6133:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6134: 
1.596.2.12.2.  8(raebur 6135:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6136:              $default_form_data."\n".
                   6137:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6138:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6139:              '<th colspan="2">
1.572     www      6140:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6141:              '</th>'."\n".
                   6142:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6143:               &Apache::loncommon::start_data_table_row()."\n".
                   6144:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6145:               '<td> '.$sequence_selector.' </td>'.
                   6146:               &Apache::loncommon::end_data_table_row()."\n".
                   6147:               &Apache::loncommon::start_data_table_row()."\n".
                   6148:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6149:               '<td> '.$file_selector.' </td>'."\n".
                   6150:               &Apache::loncommon::end_data_table_row()."\n".
                   6151:               &Apache::loncommon::start_data_table_row()."\n".
                   6152:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6153:               '<td> '.$format_selector.' </td>'."\n".
                   6154:               &Apache::loncommon::end_data_table_row()."\n".
                   6155:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6156:               '<td> '.&mt('Options').' </td>'."\n".
                   6157:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6158:               &Apache::loncommon::end_data_table_row()."\n".
                   6159:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6160:               '<td colspan="2">'."\n".
                   6161:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6162:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6163:               '</td>'."\n".
                   6164:               &Apache::loncommon::end_data_table_row()."\n".
                   6165:               &Apache::loncommon::end_data_table()."\n".
                   6166:               '</form><br />');
                   6167:     return;
1.75      albertel 6168: }
                   6169: 
1.423     albertel 6170: =pod 
                   6171: 
                   6172: =item username_to_idmap
                   6173: 
1.556     weissno  6174:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6175:     student username:domain.
                   6176: 
                   6177:   Arguments:
                   6178: 
                   6179:     $classlist - reference to the class list hash. This is a hash
                   6180:                  keyed by student name:domain  whose elements are references
1.424     albertel 6181:                  to arrays containing various chunks of information
1.423     albertel 6182:                  about the student. (See loncoursedata for more info).
                   6183: 
                   6184:   Returns
                   6185:     %idmap - the constructed hash
                   6186: 
                   6187: =cut
                   6188: 
1.82      albertel 6189: sub username_to_idmap {
                   6190:     my ($classlist)= @_;
                   6191:     my %idmap;
                   6192:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6193:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6194:5):         unless ($id eq '') {
                   6195:5):             if (!exists($idmap{$id})) {
                   6196:5):                 $idmap{$id} = $student;
                   6197:5):             } else {
                   6198:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6199:5):                 if ($status eq 'Active') {
                   6200:5):                     $idmap{$id} = $student;
                   6201:5):                 }
                   6202:5):             }
                   6203:5):         }
1.82      albertel 6204:     }
                   6205:     return %idmap;
                   6206: }
1.423     albertel 6207: 
                   6208: =pod
                   6209: 
1.424     albertel 6210: =item scantron_fixup_scanline
1.423     albertel 6211: 
                   6212:    Process a requested correction to a scanline.
                   6213: 
                   6214:   Arguments:
1.596.2.12.2.  9(raebur 6215:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6216:     $scan_data         - hash of correction information 
                   6217:                           (see &scantron_getfile())
                   6218:     $line              - existing scanline
                   6219:     $whichline         - line number of the passed in scanline
                   6220:     $field             - type of change to process 
                   6221:                          (either 
1.573     bisitz   6222:                           'ID'     -> correct the student/employee ID
1.423     albertel 6223:                           'CODE'   -> correct the CODE
                   6224:                           'answer' -> fixup the submitted answers)
                   6225:     
                   6226:    $args               - hash of additional info,
                   6227:                           - 'ID' 
                   6228:                                'newid' -> studentID to use in replacement
1.424     albertel 6229:                                           of existing one
1.423     albertel 6230:                           - 'CODE' 
                   6231:                                'CODE_ignore_dup' - set to true if duplicates
                   6232:                                                    should be ignored.
                   6233: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6234:                                         if the existing unfound code should
1.423     albertel 6235:                                         be used as is
                   6236:                           - 'answer'
                   6237:                                'response' - new answer or 'none' if blank
                   6238:                                'question' - the bubble line to change
1.503     raeburn  6239:                                'questionnum' - the question identifier,
                   6240:                                                may include subquestion. 
1.423     albertel 6241: 
                   6242:   Returns:
                   6243:     $line - the modified scanline
                   6244: 
                   6245:   Side effects: 
                   6246:     $scan_data - may be updated
                   6247: 
                   6248: =cut
                   6249: 
1.82      albertel 6250: 
1.157     albertel 6251: sub scantron_fixup_scanline {
                   6252:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6253:     if ($field eq 'ID') {
                   6254: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6255: 	    return ($line,1,'New value too large');
1.157     albertel 6256: 	}
                   6257: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6258: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6259: 				     $args->{'newid'});
                   6260: 	}
                   6261: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6262: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6263: 	if ($args->{'newid'}=~/^\s*$/) {
                   6264: 	    &scan_data($scan_data,"$whichline.user",
                   6265: 		       $args->{'username'}.':'.$args->{'domain'});
                   6266: 	}
1.186     albertel 6267:     } elsif ($field eq 'CODE') {
1.192     albertel 6268: 	if ($args->{'CODE_ignore_dup'}) {
                   6269: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6270: 	}
                   6271: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6272: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6273: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6274: 		return ($line,1,'New CODE value too large');
                   6275: 	    }
                   6276: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6277: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6278: 	    }
                   6279: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6280: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6281: 	}
1.157     albertel 6282:     } elsif ($field eq 'answer') {
1.497     foxr     6283: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6284: 	my $off=$scantron_config->{'Qoff'};
                   6285: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6286: 	my $answer=${off}x$length;
                   6287: 	if ($args->{'response'} eq 'none') {
                   6288: 	    &scan_data($scan_data,
1.503     raeburn  6289: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6290: 	} else {
                   6291: 	    if ($on eq 'letter') {
                   6292: 		my @alphabet=('A'..'Z');
                   6293: 		$answer=$alphabet[$args->{'response'}];
                   6294: 	    } elsif ($on eq 'number') {
                   6295: 		$answer=$args->{'response'}+1;
                   6296: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6297: 	    } else {
1.497     foxr     6298: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6299: 	    }
1.497     foxr     6300: 	    &scan_data($scan_data,
1.503     raeburn  6301: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6302: 	}
1.497     foxr     6303: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6304: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6305:     }
                   6306:     return $line;
                   6307: }
1.423     albertel 6308: 
                   6309: =pod
                   6310: 
                   6311: =item scan_data
                   6312: 
                   6313:     Edit or look up  an item in the scan_data hash.
                   6314: 
                   6315:   Arguments:
                   6316:     $scan_data  - The hash (see scantron_getfile)
                   6317:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6318:                   scantronfilename_key).
1.423     albertel 6319:     $data        - New value of the hash entry.
                   6320:     $delete      - If true, the entry is removed from the hash.
                   6321: 
                   6322:   Returns:
                   6323:     The new value of the hash table field (undefined if deleted).
                   6324: 
                   6325: =cut
                   6326: 
                   6327: 
1.157     albertel 6328: sub scan_data {
                   6329:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6330:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6331:     if (defined($value)) {
                   6332: 	$scan_data->{$filename.'_'.$key} = $value;
                   6333:     }
                   6334:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6335:     return $scan_data->{$filename.'_'.$key};
                   6336: }
1.423     albertel 6337: 
1.495     albertel 6338: # ----- These first few routines are general use routines.----
                   6339: 
                   6340: # Return the number of occurences of a pattern in a string.
                   6341: 
                   6342: sub occurence_count {
                   6343:     my ($string, $pattern) = @_;
                   6344: 
                   6345:     my @matches = ($string =~ /$pattern/g);
                   6346: 
                   6347:     return scalar(@matches);
                   6348: }
                   6349: 
                   6350: 
                   6351: # Take a string known to have digits and convert all the
                   6352: # digits into letters in the range J,A..I.
                   6353: 
                   6354: sub digits_to_letters {
                   6355:     my ($input) = @_;
                   6356: 
                   6357:     my @alphabet = ('J', 'A'..'I');
                   6358: 
                   6359:     my @input    = split(//, $input);
                   6360:     my $output ='';
                   6361:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6362: 	if ($input[$i] =~ /\d/) {
                   6363: 	    $output .= $alphabet[$input[$i]];
                   6364: 	} else {
                   6365: 	    $output .= $input[$i];
                   6366: 	}
                   6367:     }
                   6368:     return $output;
                   6369: }
                   6370: 
1.423     albertel 6371: =pod 
                   6372: 
                   6373: =item scantron_parse_scanline
                   6374: 
                   6375:   Decodes a scanline from the selected scantron file
                   6376: 
                   6377:  Arguments:
                   6378:     line             - The text of the scantron file line to process
                   6379:     whichline        - Line number
                   6380:     scantron_config  - Hash describing the format of the scantron lines.
                   6381:     scan_data        - Hash of extra information about the scanline
                   6382:                        (see scantron_getfile for more information)
                   6383:     just_header      - True if should not process question answers but only
                   6384:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6385:3):     randomorder      - True if randomorder in use
                   6386:3):     randompick       - True if randompick in use
                   6387:3):     sequence         - Exam folder URL
                   6388:3):     master_seq       - Ref to array containing symbs in exam folder
                   6389:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6390:3):                        (corresponding values are resource objects)
                   6391:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6392:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6393:3):                        are refs to an array of resource objects, ordered
                   6394:3):                        according to order used for CODE, when randomorder
                   6395:3):                        and or randompick are in use.
                   6396:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6397:3):                        for current line to question number used for same question
                   6398:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6399:3):     startline        - Ref to hash where key is question number (0 is first)
                   6400:3):                        and value is number of first bubble line for current 
                   6401:3):                        student or code-based randompick and/or randomorder.
                   6402:3):     totalref         - Ref of scalar used to score total number of bubble
                   6403:3):                        lines needed for responses in a scan line (used when
                   6404:3):                        randompick in use. 
                   6405:3): 
1.423     albertel 6406:  Returns:
                   6407:    Hash containing the result of parsing the scanline
                   6408: 
                   6409:    Keys are all proceeded by the string 'scantron.'
                   6410: 
                   6411:        CODE    - the CODE in use for this scanline
                   6412:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6413:                  by the operator
                   6414:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6415:                             CODEs were selected, but the usage has been
                   6416:                             forced by the operator
1.556     weissno  6417:        ID  - student/employee ID
1.423     albertel 6418:        PaperID - if used, the ID number printed on the sheet when the 
                   6419:                  paper was scanned
                   6420:        FirstName - first name from the sheet
                   6421:        LastName  - last name from the sheet
                   6422: 
                   6423:      if just_header was not true these key may also exist
                   6424: 
1.447     foxr     6425:        missingerror - a list of bubble ranges that are considered to be answers
                   6426:                       to a single question that don't have any bubbles filled in.
                   6427:                       Of the form questionnumber:firstbubblenumber:count.
                   6428:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6429:                       to a single question that have more than one bubble filled in.
                   6430:                       Of the form questionnumber::firstbubblenumber:count
                   6431:    
                   6432:                 In the above, count is the number of bubble responses in the
                   6433:                 input line needed to represent the possible answers to the question.
                   6434:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6435:                 per line would have count = 2.
                   6436: 
1.423     albertel 6437:        maxquest     - the number of the last bubble line that was parsed
                   6438: 
                   6439:        (<number> starts at 1)
                   6440:        <number>.answer - zero or more letters representing the selected
                   6441:                          letters from the scanline for the bubble line 
                   6442:                          <number>.
                   6443:                          if blank there was either no bubble or there where
                   6444:                          multiple bubbles, (consult the keys missingerror and
                   6445:                          doubleerror if this is an error condition)
                   6446: 
                   6447: =cut
                   6448: 
1.82      albertel 6449: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6450:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6451:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6452:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6453: 
1.82      albertel 6454:     my %record;
1.596.2.12.2.  6(raebur 6455:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6456:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6457: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6458: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6459: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6460: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6461: 	    $record{'scantron.CODE'}=substr($data,
                   6462: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6463: 					    $$scantron_config{'CODElength'});
1.191     albertel 6464: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6465: 		$record{'scantron.useCODE'}=1;
                   6466: 	    }
1.192     albertel 6467: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6468: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6469: 	    }
1.82      albertel 6470: 	} else {
                   6471: 	    #FIXME interpret first N questions
                   6472: 	}
                   6473:     }
1.83      albertel 6474:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6475: 				  $$scantron_config{'IDlength'});
1.157     albertel 6476:     $record{'scantron.PaperID'}=
                   6477: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6478: 	       $$scantron_config{'PaperIDlength'});
                   6479:     $record{'scantron.FirstName'}=
                   6480: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6481: 	       $$scantron_config{'FirstNamelength'});
                   6482:     $record{'scantron.LastName'}=
                   6483: 	substr($data,$$scantron_config{'LastName'}-1,
                   6484: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6485:     if ($just_header) { return \%record; }
1.194     albertel 6486: 
1.82      albertel 6487:     my @alphabet=('A'..'Z');
                   6488:     my $questnum=0;
1.447     foxr     6489:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6490: 
1.596.2.12.2.  6(raebur 6491:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6492:3):     if ($randompick || $randomorder) {
                   6493:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6494:3):                                          $master_seq,$symb_to_resource,
                   6495:3):                                          $partids_by_symb,$orderedforcode,
                   6496:3):                                          $respnumlookup,$startline);
                   6497:3):         if ($total) {
                   6498:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6499:3):         }
                   6500:3):         if (ref($totalref)) {
                   6501:3):             $$totalref = $total;
                   6502:3):         }
                   6503:3):     }
                   6504:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6505:     chomp($questions);		# Get rid of any trailing \n.
                   6506:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6507:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6508:3):         my $answers_needed;
                   6509:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6510:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6511:3):         } else {
                   6512:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6513:3):         }
1.503     raeburn  6514:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6515:                              || 1;
                   6516:         $questnum++;
                   6517:         my $quest_id = $questnum;
                   6518:         my $currentquest = substr($questions,0,$answer_length);
                   6519:         $questions       = substr($questions,$answer_length);
                   6520:         if (length($currentquest) < $answer_length) { next; }
                   6521: 
1.596.2.12.2.  6(raebur 6522:3):         my $subdivided;
                   6523:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6524:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6525:3):         } else {
                   6526:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6527:3):         }
                   6528:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6529:             my $subquestnum = 1;
                   6530:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6531:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6532:             foreach my $subans (@subanswers_needed) {
                   6533:                 my $subans_length =
                   6534:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6535:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6536:                 $subquestions   = substr($subquestions,$subans_length);
                   6537:                 $quest_id = "$questnum.$subquestnum";
                   6538:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6539:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6540:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6541:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6542:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6543:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6544:                 } else {
                   6545:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6546:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6547:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6548:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6549:                 }
                   6550:                 $subquestnum ++;
                   6551:             }
                   6552:         } else {
                   6553:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6554:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6555:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6556:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6557:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6558:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6559:             } else {
                   6560:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6561:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6562:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6563:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6564:             }
                   6565:         }
                   6566:     }
                   6567:     $record{'scantron.maxquest'}=$questnum;
                   6568:     return \%record;
                   6569: }
1.447     foxr     6570: 
1.596.2.12.2.  6(raebur 6571:3): sub get_master_seq {
                   6572:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6573:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6574:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6575:3):     my $resource_error;
                   6576:3):     foreach my $resource (@{$resources}) {
                   6577:3):         my $ressymb;
                   6578:3):         if (ref($resource)) {
                   6579:3):             $ressymb = $resource->symb();
                   6580:3):             push(@{$master_seq},$ressymb);
                   6581:3):             $symb_to_resource->{$ressymb} = $resource;
                   6582:3):         } else {
                   6583:3):             $resource_error = 1;
                   6584:3):             last;
                   6585:3):         }
                   6586:3):     }
                   6587:3):     return $resource_error;
                   6588:3): }
                   6589:3): 
                   6590:3): sub get_respnum_lookups {
                   6591:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6592:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6593:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6594:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6595:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6596:3):                    (ref($startline) eq 'HASH'));
                   6597:3):     my ($user,$scancode);
                   6598:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6599:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6600:3):         $scancode = $record->{'scantron.CODE'};
                   6601:3):     } else {
                   6602:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6603:3):     }
                   6604:3):     my @mapresources =
                   6605:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6606:3):                      $orderedforcode);
                   6607:3):     my $total = 0;
                   6608:3):     my $count = 0;
                   6609:3):     foreach my $resource (@mapresources) {
                   6610:3):         my $id = $resource->id();
                   6611:3):         my $symb = $resource->symb();
                   6612:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6613:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6614:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6615:3):                 if ($respnum ne '') {
                   6616:3):                     $respnumlookup->{$count} = $respnum;
                   6617:3):                     $startline->{$count} = $total;
                   6618:3):                     $total += $bubble_lines_per_response{$respnum};
                   6619:3):                     $count ++;
                   6620:3):                 }
                   6621:3):             }
                   6622:3):         }
                   6623:3):     }
                   6624:3):     return $total;
                   6625:3): }
                   6626:3): 
1.503     raeburn  6627: sub scantron_validator_lettnum {
                   6628:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6629:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6630:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6631: 
                   6632:     # Qon 'letter' implies for each slot in currquest we have:
                   6633:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6634:     #    about anything else (esp. a value of Qoff) for missing
                   6635:     #    bubbles.
                   6636:     #
                   6637:     # Qon 'number' implies each slot gives a digit that indexes the
                   6638:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6639:     #    and * or ? for double bubbles on a single line.
                   6640:     #
1.447     foxr     6641: 
1.503     raeburn  6642:     my $matchon;
                   6643:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6644:         $matchon = '[A-Z]';
                   6645:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6646:         $matchon = '\d';
                   6647:     }
                   6648:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6649:3):     my $responsenum = $questnum-1;
                   6650:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6651:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6652:3):     }
                   6653:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6654:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6655:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6656:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6657:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6658:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6659:         my @singlelines = split('',$currquest);
                   6660:         foreach my $entry (@singlelines) {
                   6661:             $occurrences = &occurence_count($entry,$matchon);
                   6662:             if ($occurrences > 1) {
                   6663:                 last;
                   6664:             }
1.596.2.12.2.  6(raebur 6665:3):         }
1.503     raeburn  6666:     } else {
                   6667:         $occurrences = &occurence_count($currquest,$matchon); 
                   6668:     }
                   6669:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6670:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6671:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6672:             my $bubble = substr($currquest,$ans,1);
                   6673:             if ($bubble =~ /$matchon/ ) {
                   6674:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6675:                     if ($bubble == 0) {
                   6676:                         $bubble = 10; 
                   6677:                     }
                   6678:                     $record->{"scantron.$ansnum.answer"} = 
                   6679:                         $alphabet->[$bubble-1];
                   6680:                 } else {
                   6681:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6682:                 }
                   6683:             } else {
                   6684:                 $record->{"scantron.$ansnum.answer"}='';
                   6685:             }
                   6686:             $ansnum++;
                   6687:         }
                   6688:     } elsif (!defined($currquest)
                   6689:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6690:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6691:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6692:             $record->{"scantron.$ansnum.answer"}='';
                   6693:             $ansnum++;
                   6694:         }
                   6695:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6696:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6697:         }
                   6698:     } else {
                   6699:         if ($$scantron_config{'Qon'} eq 'number') {
                   6700:             $currquest = &digits_to_letters($currquest);            
                   6701:         }
                   6702:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6703:             my $bubble = substr($currquest,$ans,1);
                   6704:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6705:             $ansnum++;
                   6706:         }
                   6707:     }
                   6708:     return $ansnum;
                   6709: }
1.447     foxr     6710: 
1.503     raeburn  6711: sub scantron_validator_positional {
                   6712:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6713:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6714:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6715: 
1.503     raeburn  6716:     # Otherwise there's a positional notation;
                   6717:     # each bubble line requires Qlength items, and there are filled in
                   6718:     # bubbles for each case where there 'Qon' characters.
                   6719:     #
1.447     foxr     6720: 
1.503     raeburn  6721:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6722: 
1.503     raeburn  6723:     # If the split only gives us one element.. the full length of the
                   6724:     # answer string, no bubbles are filled in:
1.447     foxr     6725: 
1.507     raeburn  6726:     if ($answers_needed eq '') {
                   6727:         return;
                   6728:     }
                   6729: 
1.503     raeburn  6730:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6731:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6732:             $record->{"scantron.$ansnum.answer"}='';
                   6733:             $ansnum++;
                   6734:         }
                   6735:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6736:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6737:         }
                   6738:     } elsif (scalar(@array) == 2) {
                   6739:         my $location = length($array[0]);
                   6740:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6741:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6742:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6743:             if ($ans eq $line_num) {
                   6744:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6745:             } else {
                   6746:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6747:             }
                   6748:             $ansnum++;
                   6749:          }
                   6750:     } else {
                   6751:         #  If there's more than one instance of a bubble character
                   6752:         #  That's a double bubble; with positional notation we can
                   6753:         #  record all the bubbles filled in as well as the
                   6754:         #  fact this response consists of multiple bubbles.
                   6755:         #
1.596.2.12.2.  6(raebur 6756:3):         my $responsenum = $questnum-1;
                   6757:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6758:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6759:3):         }
                   6760:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6761:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6762:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6763:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6764:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6765:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6766:             my $doubleerror = 0;
                   6767:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6768:                    (!$doubleerror)) {
                   6769:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6770:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6771:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6772:                if (length(@currarray) > 2) {
                   6773:                    $doubleerror = 1;
                   6774:                } 
                   6775:             }
                   6776:             if ($doubleerror) {
                   6777:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6778:             }
                   6779:         } else {
                   6780:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6781:         }
                   6782:         my $item = $ansnum;
                   6783:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6784:             $record->{"scantron.$item.answer"} = '';
                   6785:             $item ++;
                   6786:         }
1.447     foxr     6787: 
1.503     raeburn  6788:         my @ans=@array;
                   6789:         my $i=0;
                   6790:         my $increment = 0;
                   6791:         while ($#ans) {
                   6792:             $i+=length($ans[0]) + $increment;
                   6793:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6794:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6795:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6796:             shift(@ans);
                   6797:             $increment = 1;
                   6798:         }
                   6799:         $ansnum += $answers_needed;
1.82      albertel 6800:     }
1.503     raeburn  6801:     return $ansnum;
1.82      albertel 6802: }
                   6803: 
1.423     albertel 6804: =pod
                   6805: 
                   6806: =item scantron_add_delay
                   6807: 
                   6808:    Adds an error message that occurred during the grading phase to a
                   6809:    queue of messages to be shown after grading pass is complete
                   6810: 
                   6811:  Arguments:
1.424     albertel 6812:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6813:    $scanline    - the scanline that caused the error
                   6814:    $errormesage - the error message
                   6815:    $errorcode   - a numeric code for the error
                   6816: 
                   6817:  Side Effects:
1.424     albertel 6818:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6819: 
                   6820: =cut
                   6821: 
1.82      albertel 6822: sub scantron_add_delay {
1.140     albertel 6823:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6824:     push(@$delayqueue,
                   6825: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6826: 	  'ecode' => $errorcode }
                   6827: 	 );
1.82      albertel 6828: }
                   6829: 
1.423     albertel 6830: =pod
                   6831: 
                   6832: =item scantron_find_student
                   6833: 
1.424     albertel 6834:    Finds the username for the current scanline
                   6835: 
                   6836:   Arguments:
                   6837:    $scantron_record - hash result from scantron_parse_scanline
                   6838:    $scan_data       - hash of correction information 
                   6839:                       (see &scantron_getfile() form more information)
                   6840:    $idmap           - hash from &username_to_idmap()
                   6841:    $line            - number of current scanline
                   6842:  
                   6843:   Returns:
                   6844:    Either 'username:domain' or undef if unknown
                   6845: 
1.423     albertel 6846: =cut
                   6847: 
1.82      albertel 6848: sub scantron_find_student {
1.157     albertel 6849:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6850:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6851:     if ($scanID =~ /^\s*$/) {
                   6852:  	return &scan_data($scan_data,"$line.user");
                   6853:     }
1.83      albertel 6854:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6855:  	if (lc($id) eq lc($scanID)) {
                   6856:  	    return $$idmap{$id};
                   6857:  	}
1.83      albertel 6858:     }
                   6859:     return undef;
                   6860: }
                   6861: 
1.423     albertel 6862: =pod
                   6863: 
                   6864: =item scantron_filter
                   6865: 
1.424     albertel 6866:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6867:    hidden resources was selected
                   6868: 
1.423     albertel 6869: =cut
                   6870: 
1.83      albertel 6871: sub scantron_filter {
                   6872:     my ($curres)=@_;
1.331     albertel 6873: 
                   6874:     if (ref($curres) && $curres->is_problem()) {
                   6875: 	# if the user has asked to not have either hidden
                   6876: 	# or 'randomout' controlled resources to be graded
                   6877: 	# don't include them
                   6878: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6879: 	    && $curres->randomout) {
                   6880: 	    return 0;
                   6881: 	}
1.83      albertel 6882: 	return 1;
                   6883:     }
                   6884:     return 0;
1.82      albertel 6885: }
                   6886: 
1.423     albertel 6887: =pod
                   6888: 
                   6889: =item scantron_process_corrections
                   6890: 
1.424     albertel 6891:    Gets correction information out of submitted form data and corrects
                   6892:    the scanline
                   6893: 
1.423     albertel 6894: =cut
                   6895: 
1.157     albertel 6896: sub scantron_process_corrections {
                   6897:     my ($r) = @_;
1.596.2.12.2.  9(raebur 6898:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6899:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6900:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6901:     my $which=$env{'form.scantron_line'};
1.200     albertel 6902:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6903:     my ($skip,$err,$errmsg);
1.257     albertel 6904:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6905: 	$skip=1;
1.257     albertel 6906:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6907: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6908: 	    $env{'form.scantron_domain'};
1.157     albertel 6909: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6910: 	($line,$err,$errmsg)=
                   6911: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6912: 				     'ID',{'newid'=>$newid,
1.257     albertel 6913: 				    'username'=>$env{'form.scantron_username'},
                   6914: 				    'domain'=>$env{'form.scantron_domain'}});
                   6915:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6916: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6917: 	my $newCODE;
1.192     albertel 6918: 	my %args;
1.190     albertel 6919: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6920: 	    $newCODE='use_unfound';
1.190     albertel 6921: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6922: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6923: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6924: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6925: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6926: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6927: 	}
1.257     albertel 6928: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6929: 	    $args{'CODE_ignore_dup'}=1;
                   6930: 	}
                   6931: 	$args{'CODE'}=$newCODE;
1.186     albertel 6932: 	($line,$err,$errmsg)=
                   6933: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6934: 				     'CODE',\%args);
1.257     albertel 6935:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6936: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6937: 	    ($line,$err,$errmsg)=
                   6938: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6939: 					 $which,'answer',
                   6940: 					 { 'question'=>$question,
1.503     raeburn  6941: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6942:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6943: 	    if ($err) { last; }
                   6944: 	}
                   6945:     }
                   6946:     if ($err) {
1.596.2.12.2.  0(raebur 6947:3): 	$r->print(
                   6948:3):             '<p class="LC_error">'
                   6949:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6950:3):                 $errmsg)
          1(raebur 6951:3):            .'</p>');
1.157     albertel 6952:     } else {
1.200     albertel 6953: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6954: 	&scantron_putfile($scanlines,$scan_data);
                   6955:     }
                   6956: }
                   6957: 
1.423     albertel 6958: =pod
                   6959: 
                   6960: =item reset_skipping_status
                   6961: 
1.424     albertel 6962:    Forgets the current set of remember skipped scanlines (and thus
                   6963:    reverts back to considering all lines in the
                   6964:    scantron_skipped_<filename> file)
                   6965: 
1.423     albertel 6966: =cut
                   6967: 
1.200     albertel 6968: sub reset_skipping_status {
                   6969:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6970:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6971:     &scantron_putfile(undef,$scan_data);
                   6972: }
                   6973: 
1.423     albertel 6974: =pod
                   6975: 
                   6976: =item start_skipping
                   6977: 
1.424     albertel 6978:    Marks a scanline to be skipped. 
                   6979: 
1.423     albertel 6980: =cut
                   6981: 
1.376     albertel 6982: sub start_skipping {
1.200     albertel 6983:     my ($scan_data,$i)=@_;
                   6984:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6985:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6986: 	$remembered{$i}=2;
                   6987:     } else {
                   6988: 	$remembered{$i}=1;
                   6989:     }
1.200     albertel 6990:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6991: }
                   6992: 
1.423     albertel 6993: =pod
                   6994: 
                   6995: =item should_be_skipped
                   6996: 
1.424     albertel 6997:    Checks whether a scanline should be skipped.
                   6998: 
1.423     albertel 6999: =cut
                   7000: 
1.200     albertel 7001: sub should_be_skipped {
1.376     albertel 7002:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7003:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7004: 	# not redoing old skips
1.376     albertel 7005: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7006: 	return 0;
                   7007:     }
                   7008:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7009: 
                   7010:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7011: 	return 0;
                   7012:     }
1.200     albertel 7013:     return 1;
                   7014: }
                   7015: 
1.423     albertel 7016: =pod
                   7017: 
                   7018: =item remember_current_skipped
                   7019: 
1.424     albertel 7020:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7021:    file and remembers them into scan_data for later use.
                   7022: 
1.423     albertel 7023: =cut
                   7024: 
1.200     albertel 7025: sub remember_current_skipped {
                   7026:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7027:     my %to_remember;
                   7028:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7029: 	if ($scanlines->{'skipped'}[$i]) {
                   7030: 	    $to_remember{$i}=1;
                   7031: 	}
                   7032:     }
1.376     albertel 7033: 
1.200     albertel 7034:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7035:     &scantron_putfile(undef,$scan_data);
                   7036: }
                   7037: 
1.423     albertel 7038: =pod
                   7039: 
                   7040: =item check_for_error
                   7041: 
1.424     albertel 7042:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7043:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7044:     something went wrong.
                   7045: 
1.423     albertel 7046: =cut
                   7047: 
1.200     albertel 7048: sub check_for_error {
                   7049:     my ($r,$result)=@_;
                   7050:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7051: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7052:     }
                   7053: }
1.157     albertel 7054: 
1.423     albertel 7055: =pod
                   7056: 
                   7057: =item scantron_warning_screen
                   7058: 
1.424     albertel 7059:    Interstitial screen to make sure the operator has selected the
                   7060:    correct options before we start the validation phase.
                   7061: 
1.423     albertel 7062: =cut
                   7063: 
1.203     albertel 7064: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7065:0):     my ($button_text,$symb)=@_;
1.257     albertel 7066:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7067:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7068:     my $CODElist;
1.284     albertel 7069:     if ($scantron_config{'CODElocation'} &&
                   7070: 	$scantron_config{'CODEstart'} &&
                   7071: 	$scantron_config{'CODElength'}) {
                   7072: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7073:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7074: 	$CODElist=
1.492     albertel 7075: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7076: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7077:     }
1.596.2.12.2.  (raeburn 7078:):     my $lastbubblepoints;
                   7079:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7080:):         $lastbubblepoints =
                   7081:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7082:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7083:):     }
1.492     albertel 7084:     return ('
1.203     albertel 7085: <p>
1.492     albertel 7086: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7087:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7088: </p>
                   7089: <table>
1.492     albertel 7090: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7091: <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 7092:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7093: </table>
1.596.2.12.2.  1(raebur 7094:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7095: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 7096: 
                   7097: <br />
1.492     albertel 7098: ');
1.203     albertel 7099: }
                   7100: 
1.423     albertel 7101: =pod
                   7102: 
                   7103: =item scantron_do_warning
                   7104: 
1.424     albertel 7105:    Check if the operator has picked something for all required
                   7106:    fields. Error out if something is missing.
                   7107: 
1.423     albertel 7108: =cut
                   7109: 
1.203     albertel 7110: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7111:0):     my ($r,$symb)=@_;
1.203     albertel 7112:     if (!$symb) {return '';}
1.324     albertel 7113:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7114:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7115:     if ( $env{'form.selectpage'} eq '' ||
                   7116: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7117: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7118: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7119: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7120: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7121: 	} 
1.257     albertel 7122: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7123: 	    $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 7124: 	} 
1.257     albertel 7125: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7126: 	    $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 7127: 	} 
                   7128:     } else {
1.596.2.12.2.  1(raebur 7129:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7130:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7131: 	$r->print('
1.596.2.12.2.  (raeburn 7132:): '.$warning.$bubbledbyhand.'
1.492     albertel 7133: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7134: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7135: ');
1.237     albertel 7136:     }
1.596.2.12.2.  1(raebur 7137:0):     $r->print("</form><br />");
1.203     albertel 7138:     return '';
                   7139: }
                   7140: 
1.423     albertel 7141: =pod
                   7142: 
                   7143: =item scantron_form_start
                   7144: 
1.424     albertel 7145:     html hidden input for remembering all selected grading options
                   7146: 
1.423     albertel 7147: =cut
                   7148: 
1.203     albertel 7149: sub scantron_form_start {
                   7150:     my ($max_bubble)=@_;
                   7151:     my $result= <<SCANTRONFORM;
                   7152: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7153:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7154:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7155:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7156:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7157:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7158:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7159:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7160:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7161:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7162: SCANTRONFORM
1.447     foxr     7163: 
                   7164:   my $line = 0;
                   7165:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7166:        my $chunk =
                   7167: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7168:        $chunk .=
                   7169: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7170:        $chunk .= 
                   7171:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7172:        $chunk .=
                   7173:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7174:3):        $chunk .=
                   7175:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7176:        $result .= $chunk;
                   7177:        $line++;
1.596.2.12.2.  6(raebur 7178:3):     }
1.203     albertel 7179:     return $result;
                   7180: }
                   7181: 
1.423     albertel 7182: =pod
                   7183: 
                   7184: =item scantron_validate_file
                   7185: 
1.596.2.6  raeburn  7186:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7187: 
                   7188:     Also processes any necessary information resets that need to
                   7189:     occur before validation begins (ignore previous corrections,
                   7190:     restarting the skipped records processing)
                   7191: 
1.423     albertel 7192: =cut
                   7193: 
1.157     albertel 7194: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7195:0):     my ($r,$symb) = @_;
1.157     albertel 7196:     if (!$symb) {return '';}
1.324     albertel 7197:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7198:     
1.596.2.12.2.  0(raebur 7199:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7200:     # them when doing the corrections reset
1.257     albertel 7201:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7202: 	&reset_skipping_status();
                   7203:     }
1.257     albertel 7204:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7205: 	&remember_current_skipped();
1.257     albertel 7206: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7207:     }
                   7208: 
1.257     albertel 7209:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7210: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7211: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7212: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7213: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7214:     }
1.200     albertel 7215: 
1.257     albertel 7216:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7217: 	&scantron_process_corrections($r);
                   7218:     }
1.503     raeburn  7219:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7220:     #get the student pick code ready
                   7221:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7222:     my $nav_error;
1.596.2.12.2.  9(raebur 7223:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7224:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7225:     if ($nav_error) {
                   7226:         $r->print(&navmap_errormsg());
                   7227:         return '';
                   7228:     }
1.203     albertel 7229:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7230:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7231:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7232:):     }
1.157     albertel 7233:     $r->print($result);
                   7234:     
1.334     albertel 7235:     my @validate_phases=( 'sequence',
                   7236: 			  'ID',
1.157     albertel 7237: 			  'CODE',
                   7238: 			  'doublebubble',
                   7239: 			  'missingbubbles');
1.257     albertel 7240:     if (!$env{'form.validatepass'}) {
                   7241: 	$env{'form.validatepass'} = 0;
1.157     albertel 7242:     }
1.257     albertel 7243:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7244: 
1.448     foxr     7245: 
1.157     albertel 7246:     my $stop=0;
                   7247:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7248: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7249: 	$r->rflush();
1.596.2.12.2.  6(raebur 7250:3): 
1.157     albertel 7251: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7252: 	{
                   7253: 	    no strict 'refs';
                   7254: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7255: 	}
                   7256:     }
                   7257:     if (!$stop) {
1.596.2.12.2.  1(raebur 7258:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7259: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7260:                   $warning.
                   7261:                   &mt('Perform verification for each student after storage of submissions?').
                   7262:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7263:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7264:                   ('&nbsp;'x3).'<label>'.
                   7265:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7266:                   '</label></span><br />'.
                   7267:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7268:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7269:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7270:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7271:     } else {
                   7272: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7273: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7274:     }
                   7275:     if ($stop) {
1.334     albertel 7276: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7277: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7278: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7279: 
1.596.2.12.2.  1(raebur 7280: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 7281: 	} else {
1.503     raeburn  7282:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7283: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7284:             } else {
1.539     riegler  7285:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7286:             }
1.492     albertel 7287: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7288: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7289: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7290: 	}
1.157     albertel 7291:     }
1.596.2.12.2.  1(raebur 7292:0):     $r->print(" </form><br />");
1.157     albertel 7293:     return '';
                   7294: }
                   7295: 
1.423     albertel 7296: 
                   7297: =pod
                   7298: 
                   7299: =item scantron_remove_file
                   7300: 
1.596.2.6  raeburn  7301:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7302:    scantron_original_<filename> is never removed
                   7303: 
                   7304: 
1.423     albertel 7305: =cut
                   7306: 
1.200     albertel 7307: sub scantron_remove_file {
1.192     albertel 7308:     my ($which)=@_;
1.257     albertel 7309:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7310:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7311:     my $file='scantron_';
1.200     albertel 7312:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7313: 	$file.=$which.'_';
1.192     albertel 7314:     } else {
                   7315: 	return 'refused';
                   7316:     }
1.257     albertel 7317:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7318:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7319: }
                   7320: 
1.423     albertel 7321: 
                   7322: =pod
                   7323: 
                   7324: =item scantron_remove_scan_data
                   7325: 
1.596.2.6  raeburn  7326:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7327:    data file.  (In the case that both the are doing skipped records we need
                   7328:    to remember the old skipped lines for the time being so that element
                   7329:    persists for a while.)
                   7330: 
1.423     albertel 7331: =cut
                   7332: 
1.200     albertel 7333: sub scantron_remove_scan_data {
1.257     albertel 7334:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7335:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7336:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7337:     my @todelete;
1.257     albertel 7338:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7339:     foreach my $key (@keys) {
                   7340: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7341: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7342: 		$key=~/remember_skipping/) {
                   7343: 		next;
                   7344: 	    }
1.192     albertel 7345: 	    push(@todelete,$key);
                   7346: 	}
                   7347:     }
1.200     albertel 7348:     my $result;
1.192     albertel 7349:     if (@todelete) {
1.491     albertel 7350: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7351: 				       \@todelete,$cdom,$cname);
                   7352:     } else {
                   7353: 	$result = 'ok';
1.192     albertel 7354:     }
                   7355:     return $result;
                   7356: }
                   7357: 
1.423     albertel 7358: 
                   7359: =pod
                   7360: 
                   7361: =item scantron_getfile
                   7362: 
1.596.2.6  raeburn  7363:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7364:     the scan_data hash
                   7365:   
                   7366:   Arguments:
                   7367:     None
                   7368: 
                   7369:   Returns:
                   7370:     2 hash references
                   7371: 
                   7372:      - first one has 
                   7373:          orig      -
                   7374:          corrected -
                   7375:          skipped   -  each of which points to an array ref of the specified
                   7376:                       file broken up into individual lines
                   7377:          count     - number of scanlines
                   7378:  
                   7379:      - second is the scan_data hash possible keys are
1.425     albertel 7380:        ($number refers to scanline numbered $number and thus the key affects
                   7381:         only that scanline
                   7382:         $bubline refers to the specific bubble line element and the aspects
                   7383:         refers to that specific bubble line element)
                   7384: 
                   7385:        $number.user - username:domain to use
                   7386:        $number.CODE_ignore_dup 
                   7387:                     - ignore the duplicate CODE error 
                   7388:        $number.useCODE
                   7389:                     - use the CODE in the scanline as is
                   7390:        $number.no_bubble.$bubline
                   7391:                     - it is valid that there is no bubbled in bubble
                   7392:                       at $number $bubline
                   7393:        remember_skipping
                   7394:                     - a frozen hash containing keys of $number and values
                   7395:                       of either 
                   7396:                         1 - we are on a 'do skipped records pass' and plan
                   7397:                             on processing this line
                   7398:                         2 - we are on a 'do skipped records pass' and this
                   7399:                             scanline has been marked to skip yet again
1.424     albertel 7400: 
1.423     albertel 7401: =cut
                   7402: 
1.157     albertel 7403: sub scantron_getfile {
1.200     albertel 7404:     #FIXME really would prefer a scantron directory
1.257     albertel 7405:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7406:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7407:     my $lines;
                   7408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7409: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7410:     my %scanlines;
                   7411:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7412:     my $temp=$scanlines{'orig'};
                   7413:     $scanlines{'count'}=$#$temp;
                   7414: 
                   7415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7416: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7417:     if ($lines eq '-1') {
                   7418: 	$scanlines{'corrected'}=[];
                   7419:     } else {
                   7420: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7421:     }
                   7422:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7423: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7424:     if ($lines eq '-1') {
                   7425: 	$scanlines{'skipped'}=[];
                   7426:     } else {
                   7427: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7428:     }
1.175     albertel 7429:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7430:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7431:     my %scan_data = @tmp;
                   7432:     return (\%scanlines,\%scan_data);
                   7433: }
                   7434: 
1.423     albertel 7435: =pod
                   7436: 
                   7437: =item lonnet_putfile
                   7438: 
1.424     albertel 7439:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7440: 
                   7441:  Arguments:
                   7442:    $contents - data to store
                   7443:    $filename - filename to store $contents into
                   7444: 
                   7445:  Returns:
                   7446:    result value from &Apache::lonnet::finishuserfileupload
                   7447: 
1.423     albertel 7448: =cut
                   7449: 
1.157     albertel 7450: sub lonnet_putfile {
                   7451:     my ($contents,$filename)=@_;
1.257     albertel 7452:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7453:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7454:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7455:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7456: 
                   7457: }
                   7458: 
1.423     albertel 7459: =pod
                   7460: 
                   7461: =item scantron_putfile
                   7462: 
1.596.2.6  raeburn  7463:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7464:     scan_data hash. (Does not modify the original version only the
                   7465:     corrected and skipped versions.
                   7466: 
                   7467:  Arguments:
                   7468:     $scanlines - hash ref that looks like the first return value from
                   7469:                  &scantron_getfile()
                   7470:     $scan_data - hash ref that looks like the second return value from
                   7471:                  &scantron_getfile()
                   7472: 
1.423     albertel 7473: =cut
                   7474: 
1.157     albertel 7475: sub scantron_putfile {
                   7476:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7477:     #FIXME really would prefer a scantron directory
1.257     albertel 7478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7480:     if ($scanlines) {
                   7481: 	my $prefix='scantron_';
1.157     albertel 7482: # no need to update orig, shouldn't change
                   7483: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7484: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7485: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7486: 			$prefix.'corrected_'.
1.257     albertel 7487: 			$env{'form.scantron_selectfile'});
1.200     albertel 7488: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7489: 			$prefix.'skipped_'.
1.257     albertel 7490: 			$env{'form.scantron_selectfile'});
1.200     albertel 7491:     }
1.175     albertel 7492:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7493: }
                   7494: 
1.423     albertel 7495: =pod
                   7496: 
                   7497: =item scantron_get_line
                   7498: 
1.424     albertel 7499:    Returns the correct version of the scanline
                   7500: 
                   7501:  Arguments:
                   7502:     $scanlines - hash ref that looks like the first return value from
                   7503:                  &scantron_getfile()
                   7504:     $scan_data - hash ref that looks like the second return value from
                   7505:                  &scantron_getfile()
                   7506:     $i         - number of the requested line (starts at 0)
                   7507: 
                   7508:  Returns:
                   7509:    A scanline, (either the original or the corrected one if it
                   7510:    exists), or undef if the requested scanline should be
                   7511:    skipped. (Either because it's an skipped scanline, or it's an
                   7512:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7513:    pass.
                   7514: 
1.423     albertel 7515: =cut
                   7516: 
1.157     albertel 7517: sub scantron_get_line {
1.200     albertel 7518:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7519:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7520:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7521:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7522:     return $scanlines->{'orig'}[$i]; 
                   7523: }
                   7524: 
1.423     albertel 7525: =pod
                   7526: 
                   7527: =item scantron_todo_count
                   7528: 
1.424     albertel 7529:     Counts the number of scanlines that need processing.
                   7530: 
                   7531:  Arguments:
                   7532:     $scanlines - hash ref that looks like the first return value from
                   7533:                  &scantron_getfile()
                   7534:     $scan_data - hash ref that looks like the second return value from
                   7535:                  &scantron_getfile()
                   7536: 
                   7537:  Returns:
                   7538:     $count - number of scanlines to process
                   7539: 
1.423     albertel 7540: =cut
                   7541: 
1.200     albertel 7542: sub get_todo_count {
                   7543:     my ($scanlines,$scan_data)=@_;
                   7544:     my $count=0;
                   7545:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7546: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7547: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7548: 	$count++;
                   7549:     }
                   7550:     return $count;
                   7551: }
                   7552: 
1.423     albertel 7553: =pod
                   7554: 
                   7555: =item scantron_put_line
                   7556: 
1.596.2.6  raeburn  7557:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7558:     data file.
                   7559: 
                   7560:  Arguments:
                   7561:     $scanlines - hash ref that looks like the first return value from
                   7562:                  &scantron_getfile()
                   7563:     $scan_data - hash ref that looks like the second return value from
                   7564:                  &scantron_getfile()
                   7565:     $i         - line number to update
                   7566:     $newline   - contents of the updated scanline
                   7567:     $skip      - if true make the line for skipping and update the
                   7568:                  'skipped' file
                   7569: 
1.423     albertel 7570: =cut
                   7571: 
1.157     albertel 7572: sub scantron_put_line {
1.200     albertel 7573:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7574:     if ($skip) {
                   7575: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7576: 	&start_skipping($scan_data,$i);
1.157     albertel 7577: 	return;
                   7578:     }
                   7579:     $scanlines->{'corrected'}[$i]=$newline;
                   7580: }
                   7581: 
1.423     albertel 7582: =pod
                   7583: 
                   7584: =item scantron_clear_skip
                   7585: 
1.424     albertel 7586:    Remove a line from the 'skipped' file
                   7587: 
                   7588:  Arguments:
                   7589:     $scanlines - hash ref that looks like the first return value from
                   7590:                  &scantron_getfile()
                   7591:     $scan_data - hash ref that looks like the second return value from
                   7592:                  &scantron_getfile()
                   7593:     $i         - line number to update
                   7594: 
1.423     albertel 7595: =cut
                   7596: 
1.376     albertel 7597: sub scantron_clear_skip {
                   7598:     my ($scanlines,$scan_data,$i)=@_;
                   7599:     if (exists($scanlines->{'skipped'}[$i])) {
                   7600: 	undef($scanlines->{'skipped'}[$i]);
                   7601: 	return 1;
                   7602:     }
                   7603:     return 0;
                   7604: }
                   7605: 
1.423     albertel 7606: =pod
                   7607: 
                   7608: =item scantron_filter_not_exam
                   7609: 
1.424     albertel 7610:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7611:    filter out resources that are not marked as 'exam' mode
                   7612: 
1.423     albertel 7613: =cut
                   7614: 
1.334     albertel 7615: sub scantron_filter_not_exam {
                   7616:     my ($curres)=@_;
                   7617:     
                   7618:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7619: 	# if the user has asked to not have either hidden
                   7620: 	# or 'randomout' controlled resources to be graded
                   7621: 	# don't include them
                   7622: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7623: 	    && $curres->randomout) {
                   7624: 	    return 0;
                   7625: 	}
                   7626: 	return 1;
                   7627:     }
                   7628:     return 0;
                   7629: }
                   7630: 
1.423     albertel 7631: =pod
                   7632: 
                   7633: =item scantron_validate_sequence
                   7634: 
1.424     albertel 7635:     Validates the selected sequence, checking for resource that are
                   7636:     not set to exam mode.
                   7637: 
1.423     albertel 7638: =cut
                   7639: 
1.334     albertel 7640: sub scantron_validate_sequence {
                   7641:     my ($r,$currentphase) = @_;
                   7642: 
                   7643:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7644:     unless (ref($navmap)) {
                   7645:         $r->print(&navmap_errormsg());
                   7646:         return (1,$currentphase);
                   7647:     }
1.334     albertel 7648:     my (undef,undef,$sequence)=
                   7649: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7650: 
                   7651:     my $map=$navmap->getResourceByUrl($sequence);
                   7652: 
                   7653:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7654:                                     value="ignore" />');
                   7655:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7656: 	my @resources=
                   7657: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7658: 	if (@resources) {
1.596.2.12.2.  0(raebur 7659:2): 	    $r->print('<p class="LC_warning">'
                   7660:2):                .&mt('Some resources in the sequence currently are not set to'
                   7661:2):                    .' exam mode. Grading these resources currently may not'
                   7662:2):                    .' work correctly.')
                   7663:2):                .'</p>'
                   7664:2):             );
1.334     albertel 7665: 	    return (1,$currentphase);
                   7666: 	}
                   7667:     }
                   7668: 
                   7669:     return (0,$currentphase+1);
                   7670: }
                   7671: 
1.423     albertel 7672: 
                   7673: 
1.157     albertel 7674: sub scantron_validate_ID {
                   7675:     my ($r,$currentphase) = @_;
                   7676:     
                   7677:     #get student info
                   7678:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7679:     my %idmap=&username_to_idmap($classlist);
                   7680: 
                   7681:     #get scantron line setup
1.596.2.12.2.  9(raebur 7682:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7683:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7684: 
                   7685:     my $nav_error;
1.596.2.12.2.  (raeburn 7686:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7687:     if ($nav_error) {
                   7688:         $r->print(&navmap_errormsg());
                   7689:         return(1,$currentphase);
                   7690:     }
1.157     albertel 7691: 
                   7692:     my %found=('ids'=>{},'usernames'=>{});
                   7693:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7694: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7695: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7696: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7697: 						 $scan_data);
                   7698: 	my $id=$$scan_record{'scantron.ID'};
                   7699: 	my $found;
                   7700: 	foreach my $checkid (keys(%idmap)) {
                   7701: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7702: 	}
                   7703: 	if ($found) {
                   7704: 	    my $username=$idmap{$found};
                   7705: 	    if ($found{'ids'}{$found}) {
                   7706: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7707: 					 $line,'duplicateID',$found);
1.194     albertel 7708: 		return(1,$currentphase);
1.157     albertel 7709: 	    } elsif ($found{'usernames'}{$username}) {
                   7710: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7711: 					 $line,'duplicateID',$username);
1.194     albertel 7712: 		return(1,$currentphase);
1.157     albertel 7713: 	    }
1.186     albertel 7714: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7715: 	    $found{'ids'}{$found}++;
                   7716: 	    $found{'usernames'}{$username}++;
                   7717: 	} else {
                   7718: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7719: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7720: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7721: 		    &scantron_get_correction($r,$i,$scan_record,
                   7722: 					     \%scantron_config,
                   7723: 					     $line,'duplicateID',$username);
1.194     albertel 7724: 		    return(1,$currentphase);
1.157     albertel 7725: 		} elsif (!defined($username)) {
                   7726: 		    &scantron_get_correction($r,$i,$scan_record,
                   7727: 					     \%scantron_config,
                   7728: 					     $line,'incorrectID');
1.194     albertel 7729: 		    return(1,$currentphase);
1.157     albertel 7730: 		}
                   7731: 		$found{'usernames'}{$username}++;
                   7732: 	    } else {
                   7733: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7734: 					 $line,'incorrectID');
1.194     albertel 7735: 		return(1,$currentphase);
1.157     albertel 7736: 	    }
                   7737: 	}
                   7738:     }
                   7739: 
                   7740:     return (0,$currentphase+1);
                   7741: }
                   7742: 
1.423     albertel 7743: 
1.157     albertel 7744: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7745:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7746:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7747: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7748: #to show both the current line and the previous one and allow skipping
                   7749: #the previous one or the current one
                   7750: 
1.333     albertel 7751:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7752:         $r->print(
                   7753:             '<p class="LC_warning">'
                   7754:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7755:                 "<b>$error</b>",
                   7756:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7757:            ."</p> \n");
1.157     albertel 7758:     } else {
1.596.2.6  raeburn  7759:         $r->print(
                   7760:             '<p class="LC_warning">'
                   7761:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7762:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7763:            ."</p> \n");
                   7764:     }
                   7765:     my $message =
                   7766:         '<p>'
                   7767:        .&mt('The ID on the form is [_1]',
                   7768:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7769:        .'<br />'
1.596.2.12  raeburn  7770:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7771:             $$scan_record{'scantron.LastName'},
                   7772:             $$scan_record{'scantron.FirstName'})
                   7773:        .'</p>';
1.242     albertel 7774: 
1.157     albertel 7775:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7776:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7777:                            # Array populated for doublebubble or
                   7778:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7779:                            # to validate radio button checking   
                   7780: 
1.157     albertel 7781:     if ($error =~ /ID$/) {
1.186     albertel 7782: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7783: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7784: 		      "</p>\n");
1.157     albertel 7785: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7786: 	    $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 7787: 	}
1.242     albertel 7788: 	$r->print($message);
1.492     albertel 7789: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7790: 	$r->print("\n<ul><li> ");
                   7791: 	#FIXME it would be nice if this sent back the user ID and
                   7792: 	#could do partial userID matches
                   7793: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7794: 				       'scantron_username','scantron_domain'));
                   7795: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7796:3): 	$r->print("\n:\n".
1.257     albertel 7797: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7798: 
                   7799: 	$r->print('</li>');
1.186     albertel 7800:     } elsif ($error =~ /CODE$/) {
                   7801: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7802: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7803: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7804: 	    $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 7805: 	}
1.596.2.6  raeburn  7806:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7807:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7808:                  ."</p>\n");
1.242     albertel 7809: 	$r->print($message);
1.596.2.6  raeburn  7810: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7811: 	$r->print("\n<br /> ");
1.194     albertel 7812: 	my $i=0;
1.273     albertel 7813: 	if ($error eq 'incorrectCODE' 
                   7814: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7815: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7816: 	    if ($closest > 0) {
                   7817: 		foreach my $testcode (@{$closest}) {
                   7818: 		    my $checked='';
1.569     bisitz   7819: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7820: 		    $r->print("
                   7821:    <label>
1.569     bisitz   7822:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7823:        ".&mt("Use the similar CODE [_1] instead.",
                   7824: 	    "<b><tt>".$testcode."</tt></b>")."
                   7825:     </label>
                   7826:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7827: 		    $r->print("\n<br />");
                   7828: 		    $i++;
                   7829: 		}
1.194     albertel 7830: 	    }
                   7831: 	}
1.273     albertel 7832: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7833: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7834: 	    $r->print("
                   7835:     <label>
1.569     bisitz   7836:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7837:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7838: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7839:     </label>");
1.273     albertel 7840: 	    $r->print("\n<br />");
                   7841: 	}
1.194     albertel 7842: 
1.596.2.12.2.  1(raebur 7843:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7844: function change_radio(field) {
1.190     albertel 7845:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7846:     var i;
                   7847:     for (i=0;i<slct.length;i++) {
                   7848:         if (slct[i].value==field) { slct[i].checked=true; }
                   7849:     }
                   7850: }
                   7851: ENDSCRIPT
1.187     albertel 7852: 	my $href="/adm/pickcode?".
1.359     www      7853: 	   "form=".&escape("scantronupload").
                   7854: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7855: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7856: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7857: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7858: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7859: 	    $r->print("
                   7860:     <label>
                   7861:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7862:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7863: 	     "<a target='_blank' href='$href'>","</a>")."
                   7864:     </label> 
1.558     bisitz   7865:     ".&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 7866: 	    $r->print("\n<br />");
                   7867: 	}
1.492     albertel 7868: 	$r->print("
                   7869:     <label>
                   7870:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7871:        ".&mt("Use [_1] as the CODE.",
                   7872: 	     "</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 7873: 	$r->print("\n<br /><br />");
1.157     albertel 7874:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7875: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7876: 
                   7877: 	# The form field scantron_questions is acutally a list of line numbers.
                   7878: 	# represented by this form so:
                   7879: 
1.596.2.12.2.  6(raebur 7880:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7881:3):                                                 $respnumlookup,$startline);
1.497     foxr     7882: 
1.157     albertel 7883: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7884: 		  $line_list.'" />');
1.242     albertel 7885: 	$r->print($message);
1.492     albertel 7886: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7887: 	foreach my $question (@{$arg}) {
1.503     raeburn  7888: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7889:3):                                                    $scan_record, $error,
                   7890:3):                                                    $randomorder,$randompick,
                   7891:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7892:             push(@lines_to_correct,@linenums);
1.157     albertel 7893: 	}
1.503     raeburn  7894:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7895:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7896: 	$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 7897: 	$r->print($message);
1.492     albertel 7898: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7899: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7900: 
1.503     raeburn  7901: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7902: 	# a list of question numbers. Therefore:
                   7903: 	#
                   7904: 	
1.596.2.12.2.  6(raebur 7905:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7906:3):                                                 $respnumlookup,$startline);
1.497     foxr     7907: 
1.157     albertel 7908: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7909: 		  $line_list.'" />');
1.157     albertel 7910: 	foreach my $question (@{$arg}) {
1.503     raeburn  7911: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7912:3):                                                    $scan_record, $error,
                   7913:3):                                                    $randomorder,$randompick,
                   7914:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7915:             push(@lines_to_correct,@linenums);
1.157     albertel 7916: 	}
1.503     raeburn  7917:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7918:     } else {
                   7919: 	$r->print("\n<ul>");
                   7920:     }
                   7921:     $r->print("\n</li></ul>");
1.497     foxr     7922: }
                   7923: 
1.503     raeburn  7924: sub verify_bubbles_checked {
                   7925:     my (@ansnums) = @_;
                   7926:     my $ansnumstr = join('","',@ansnums);
                   7927:     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 7928:6):     &js_escape(\$warning);
          1(raebur 7929:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  7930: function verify_bubble_radio(form) {
                   7931:     var ansnumArray = new Array ("$ansnumstr");
                   7932:     var need_bubble_count = 0;
                   7933:     for (var i=0; i<ansnumArray.length; i++) {
                   7934:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7935:             var bubble_picked = 0; 
                   7936:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7937:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7938:                     bubble_picked = 1;
                   7939:                 }
                   7940:             }
                   7941:             if (bubble_picked == 0) {
                   7942:                 need_bubble_count ++;
                   7943:             }
                   7944:         }
                   7945:     }
                   7946:     if (need_bubble_count) {
                   7947:         alert("$warning");
                   7948:         return;
                   7949:     }
                   7950:     form.submit(); 
                   7951: }
                   7952: ENDSCRIPT
                   7953:     return $output;
                   7954: }
                   7955: 
1.497     foxr     7956: =pod
                   7957: 
                   7958: =item  questions_to_line_list
1.157     albertel 7959: 
1.497     foxr     7960: Converts a list of questions into a string of comma separated
                   7961: line numbers in the answer sheet used by the questions.  This is
                   7962: used to fill in the scantron_questions form field.
                   7963: 
                   7964:   Arguments:
                   7965:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7966:3):      randomorder  - True if randomorder in use.
                   7967:3):      randompick   - True if randompick in use.
                   7968:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7969:3):                      for current line to question number used for same question
                   7970:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7971:3):      startline    - Reference to hash where key is question number (0 is first)
                   7972:3):                     and key is number of first bubble line for current student
                   7973:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7974: 
                   7975: =cut
                   7976: 
                   7977: 
                   7978: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7979:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7980:     my @lines;
                   7981: 
1.503     raeburn  7982:     foreach my $item (@{$questions}) {
                   7983:         my $question = $item;
                   7984:         my ($first,$count,$last);
                   7985:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7986:             $question = $1;
                   7987:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7988:3):             my $responsenum = $question-1;
                   7989:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7990:3):                 $responsenum = $respnumlookup->{$question-1};
                   7991:3):                 if (ref($startline) eq 'HASH') {
                   7992:3):                     $first = $startline->{$question-1} + 1;
                   7993:3):                 }
                   7994:3):             } else {
                   7995:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7996:3):             }
          7(raebur 7997:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7998:             my $subcount = 1;
                   7999:             while ($subcount<$subquestion) {
                   8000:                 $first += $subans[$subcount-1];
                   8001:                 $subcount ++;
                   8002:             }
                   8003:             $count = $subans[$subquestion-1];
                   8004:         } else {
1.596.2.12.2.  7(raebur 8005:3):             my $responsenum = $question-1;
                   8006:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8007:3):                 $responsenum = $respnumlookup->{$question-1};
                   8008:3):                 if (ref($startline) eq 'HASH') {
                   8009:3):                     $first = $startline->{$question-1} + 1;
                   8010:3):                 }
                   8011:3):             } else {
                   8012:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8013:3):             }
                   8014:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8015:         }
1.506     raeburn  8016:         $last = $first+$count-1;
1.503     raeburn  8017:         push(@lines, ($first..$last));
1.497     foxr     8018:     }
                   8019:     return join(',', @lines);
                   8020: }
                   8021: 
                   8022: =pod 
                   8023: 
                   8024: =item prompt_for_corrections
                   8025: 
                   8026: Prompts for a potentially multiline correction to the
                   8027: user's bubbling (factors out common code from scantron_get_correction
                   8028: for multi and missing bubble cases).
                   8029: 
                   8030:  Arguments:
                   8031:    $r           - Apache request object.
                   8032:    $question    - The question number to prompt for.
                   8033:    $scan_config - The scantron file configuration hash.
                   8034:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8035:    $error       - Type of error
1.596.2.12.2.  7(raebur 8036:3):    $randomorder - True if randomorder in use.
                   8037:3):    $randompick  - True if randompick in use.
                   8038:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8039:3):                     for current line to question number used for same question
                   8040:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8041:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8042:3):                   and value is number of first bubble line for current student
                   8043:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8044: 
                   8045:  Implicit inputs:
                   8046:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8047:                                   Numbered from 0 (but question numbers are from
                   8048:                                   1.
                   8049:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8050:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8051:                                   type problems render as separate sub-questions, 
1.503     raeburn  8052:                                   in exam mode. This hash contains a 
                   8053:                                   comma-separated list of the lines per 
                   8054:                                   sub-question.
1.510     raeburn  8055:    %responsetype_per_response   - essayresponse, formularesponse,
                   8056:                                   stringresponse, imageresponse, reactionresponse,
                   8057:                                   and organicresponse type problem parts can have
1.503     raeburn  8058:                                   multiple lines per response if the weight
                   8059:                                   assigned exceeds 10.  In this case, only
                   8060:                                   one bubble per line is permitted, but more 
                   8061:                                   than one line might contain bubbles, e.g.
                   8062:                                   bubbling of: line 1 - J, line 2 - J, 
                   8063:                                   line 3 - B would assign 22 points.  
1.497     foxr     8064: 
                   8065: =cut
                   8066: 
                   8067: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8068:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8069:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8070:     my ($current_line,$lines);
                   8071:     my @linenums;
                   8072:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8073:3):     my ($first,$responsenum);
1.503     raeburn  8074:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8075:         $question = $1;
                   8076:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8077:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8078:3):             $responsenum = $respnumlookup->{$question-1};
                   8079:3):             if (ref($startline) eq 'HASH') {
                   8080:3):                 $first = $startline->{$question-1};
                   8081:3):             }
                   8082:3):         } else {
                   8083:3):             $responsenum = $question-1;
          7(raebur 8084:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8085:3):         }
                   8086:3):         $current_line = $first + 1 ;
                   8087:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8088:         my $subcount = 1;
                   8089:         while ($subcount<$subquestion) {
                   8090:             $current_line += $subans[$subcount-1];
                   8091:             $subcount ++;
                   8092:         }
                   8093:         $lines = $subans[$subquestion-1];
                   8094:     } else {
1.596.2.12.2.  6(raebur 8095:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8096:3):             $responsenum = $respnumlookup->{$question-1};
                   8097:3):             if (ref($startline) eq 'HASH') {
                   8098:3):                 $first = $startline->{$question-1};
                   8099:3):             }
                   8100:3):         } else {
                   8101:3):             $responsenum = $question-1;
                   8102:3):             $first = $first_bubble_line{$responsenum};
                   8103:3):         }
                   8104:3):         $current_line = $first + 1;
                   8105:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8106:     }
1.497     foxr     8107:     if ($lines > 1) {
1.503     raeburn  8108:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8109:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8110:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8111:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8112:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8113:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8114:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8115: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  8116:         } else {
                   8117:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8118:         }
1.497     foxr     8119:     }
                   8120:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8121:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8122:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8123: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8124:         push(@linenums,$current_line);
1.497     foxr     8125: 	$current_line++;
                   8126:     }
                   8127:     if ($lines > 1) {
                   8128: 	$r->print("<hr /><br />");
                   8129:     }
1.503     raeburn  8130:     return @linenums;
1.157     albertel 8131: }
1.423     albertel 8132: 
                   8133: =pod
                   8134: 
                   8135: =item scantron_bubble_selector
                   8136:   
                   8137:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8138:    possibly showing the existing the selected bubbles if known
1.423     albertel 8139: 
                   8140:  Arguments:
                   8141:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8142:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8143:     $line        - Number of the line being displayed.
1.503     raeburn  8144:     $questionnum - Question number (may include subquestion)
                   8145:     $error       - Type of error.
1.497     foxr     8146:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8147: 
                   8148: =cut
                   8149: 
1.157     albertel 8150: sub scantron_bubble_selector {
1.503     raeburn  8151:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8152:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8153: 
                   8154:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8155:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8156:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8157:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8158:):             $max=$$scan_config{'BubblesPerRow'};
                   8159:):             if (($scmode eq 'number') && ($max > 10)) {
                   8160:):                 $max = 10;
                   8161:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8162:):                 $max = 26;
                   8163:):             }
                   8164:):         } else {
                   8165:):             $max = 10;
                   8166:):         }
                   8167:):     }
1.274     albertel 8168: 
1.157     albertel 8169:     my @alphabet=('A'..'Z');
1.503     raeburn  8170:     $r->print(&Apache::loncommon::start_data_table().
                   8171:               &Apache::loncommon::start_data_table_row());
                   8172:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8173:     for (my $i=0;$i<$max+1;$i++) {
                   8174: 	$r->print("\n".'<td align="center">');
                   8175: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8176: 	else { $r->print('&nbsp;'); }
                   8177: 	$r->print('</td>');
                   8178:     }
1.503     raeburn  8179:     $r->print(&Apache::loncommon::end_data_table_row().
                   8180:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8181:     for (my $i=0;$i<$max;$i++) {
                   8182: 	$r->print("\n".
                   8183: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8184: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8185:     }
1.503     raeburn  8186:     my $nobub_checked = ' ';
                   8187:     if ($error eq 'missingbubble') {
                   8188:         $nobub_checked = ' checked = "checked" ';
                   8189:     }
                   8190:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8191: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8192:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8193:               $line.'" value="'.$questionnum.'" /></td>');
                   8194:     $r->print(&Apache::loncommon::end_data_table_row().
                   8195:               &Apache::loncommon::end_data_table());
1.157     albertel 8196: }
                   8197: 
1.423     albertel 8198: =pod
                   8199: 
                   8200: =item num_matches
                   8201: 
1.424     albertel 8202:    Counts the number of characters that are the same between the two arguments.
                   8203: 
                   8204:  Arguments:
                   8205:    $orig - CODE from the scanline
                   8206:    $code - CODE to match against
                   8207: 
                   8208:  Returns:
                   8209:    $count - integer count of the number of same characters between the
                   8210:             two arguments
                   8211: 
1.423     albertel 8212: =cut
                   8213: 
1.194     albertel 8214: sub num_matches {
                   8215:     my ($orig,$code) = @_;
                   8216:     my @code=split(//,$code);
                   8217:     my @orig=split(//,$orig);
                   8218:     my $same=0;
                   8219:     for (my $i=0;$i<scalar(@code);$i++) {
                   8220: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8221:     }
                   8222:     return $same;
                   8223: }
                   8224: 
1.423     albertel 8225: =pod
                   8226: 
                   8227: =item scantron_get_closely_matching_CODEs
                   8228: 
1.424     albertel 8229:    Cycles through all CODEs and finds the set that has the greatest
                   8230:    number of same characters as the provided CODE
                   8231: 
                   8232:  Arguments:
                   8233:    $allcodes - hash ref returned by &get_codes()
                   8234:    $CODE     - CODE from the current scanline
                   8235: 
                   8236:  Returns:
                   8237:    2 element list
                   8238:     - first elements is number of how closely matching the best fit is 
                   8239:       (5 means best set has 5 matching characters)
                   8240:     - second element is an arrary ref containing the set of valid CODEs
                   8241:       that best fit the passed in CODE
                   8242: 
1.423     albertel 8243: =cut
                   8244: 
1.194     albertel 8245: sub scantron_get_closely_matching_CODEs {
                   8246:     my ($allcodes,$CODE)=@_;
                   8247:     my @CODEs;
                   8248:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8249: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8250:     }
                   8251: 
                   8252:     return ($#CODEs,$CODEs[-1]);
                   8253: }
                   8254: 
1.423     albertel 8255: =pod
                   8256: 
                   8257: =item get_codes
                   8258: 
1.424     albertel 8259:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8260:    set of remembered CODEs.
                   8261: 
                   8262:  Arguments:
                   8263:   $old_name - name of the set of remembered CODEs
                   8264:   $cdom     - domain of the course
                   8265:   $cnum     - internal course name
                   8266: 
                   8267:  Returns:
                   8268:   %allcodes - keys are the valid CODEs, values are all 1
                   8269: 
1.423     albertel 8270: =cut
                   8271: 
1.194     albertel 8272: sub get_codes {
1.280     foxr     8273:     my ($old_name, $cdom, $cnum) = @_;
                   8274:     if (!$old_name) {
                   8275: 	$old_name=$env{'form.scantron_CODElist'};
                   8276:     }
                   8277:     if (!$cdom) {
                   8278: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8279:     }
                   8280:     if (!$cnum) {
                   8281: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8282:     }
1.278     albertel 8283:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8284: 				    $cdom,$cnum);
                   8285:     my %allcodes;
                   8286:     if ($result{"type\0$old_name"} eq 'number') {
                   8287: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8288:     } else {
                   8289: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8290:     }
1.194     albertel 8291:     return %allcodes;
                   8292: }
                   8293: 
1.423     albertel 8294: =pod
                   8295: 
                   8296: =item scantron_validate_CODE
                   8297: 
1.424     albertel 8298:    Validates all scanlines in the selected file to not have any
                   8299:    invalid or underspecified CODEs and that none of the codes are
                   8300:    duplicated if this was requested.
                   8301: 
1.423     albertel 8302: =cut
                   8303: 
1.157     albertel 8304: sub scantron_validate_CODE {
                   8305:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8306:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8307:     if ($scantron_config{'CODElocation'} &&
                   8308: 	$scantron_config{'CODEstart'} &&
                   8309: 	$scantron_config{'CODElength'}) {
1.257     albertel 8310: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8311: 	    &FIXME_blow_up()
                   8312: 	}
                   8313:     } else {
                   8314: 	return (0,$currentphase+1);
                   8315:     }
                   8316:     
                   8317:     my %usedCODEs;
                   8318: 
1.194     albertel 8319:     my %allcodes=&get_codes();
1.186     albertel 8320: 
1.582     raeburn  8321:     my $nav_error;
1.596.2.12.2.  (raeburn 8322:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8323:     if ($nav_error) {
                   8324:         $r->print(&navmap_errormsg());
                   8325:         return(1,$currentphase);
                   8326:     }
1.447     foxr     8327: 
1.186     albertel 8328:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8329:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8330: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8331: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8332: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8333: 						 $scan_data);
                   8334: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8335: 	my $error=0;
1.224     albertel 8336: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8337: 	    &scantron_get_correction($r,$i,$scan_record,
                   8338: 				     \%scantron_config,
                   8339: 				     $line,'incorrectCODE',\%allcodes);
                   8340: 	    return(1,$currentphase);
                   8341: 	}
1.221     albertel 8342: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8343: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8344: 	    &scantron_get_correction($r,$i,$scan_record,
                   8345: 				     \%scantron_config,
1.194     albertel 8346: 				     $line,'incorrectCODE',\%allcodes);
                   8347: 	    return(1,$currentphase);
1.186     albertel 8348: 	}
1.214     albertel 8349: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8350: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8351: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8352: 	    &scantron_get_correction($r,$i,$scan_record,
                   8353: 				     \%scantron_config,
1.194     albertel 8354: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8355: 	    return(1,$currentphase);
1.186     albertel 8356: 	}
1.524     raeburn  8357: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8358:     }
1.157     albertel 8359:     return (0,$currentphase+1);
                   8360: }
                   8361: 
1.423     albertel 8362: =pod
                   8363: 
                   8364: =item scantron_validate_doublebubble
                   8365: 
1.424     albertel 8366:    Validates all scanlines in the selected file to not have any
                   8367:    bubble lines with multiple bubbles marked.
                   8368: 
1.423     albertel 8369: =cut
                   8370: 
1.157     albertel 8371: sub scantron_validate_doublebubble {
                   8372:     my ($r,$currentphase) = @_;
                   8373:     #get student info
                   8374:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8375:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8376:3):     my (undef,undef,$sequence)=
                   8377:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8378: 
                   8379:     #get scantron line setup
1.596.2.12.2.  9(raebur 8380:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8381:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8382:3): 
                   8383:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8384:3):     unless (ref($navmap)) {
                   8385:3):         $r->print(&navmap_errormsg());
                   8386:3):         return(1,$currentphase);
                   8387:3):     }
                   8388:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8389:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8390:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8391:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8392:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8393:3): 
1.583     raeburn  8394:     my $nav_error;
1.596.2.12.2.  6(raebur 8395:3):     if (ref($map)) {
                   8396:3):         $randomorder = $map->randomorder();
                   8397:3):         $randompick = $map->randompick();
                   8398:3):         if ($randomorder || $randompick) {
                   8399:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8400:3):             if ($nav_error) {
                   8401:3):                 $r->print(&navmap_errormsg());
                   8402:3):                 return(1,$currentphase);
                   8403:3):             }
                   8404:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8405:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8406:3):         }
                   8407:3):     } else {
                   8408:3):         $r->print(&navmap_errormsg());
                   8409:3):         return(1,$currentphase);
                   8410:3):     }
                   8411:3): 
          (raeburn 8412:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8413:     if ($nav_error) {
                   8414:         $r->print(&navmap_errormsg());
                   8415:         return(1,$currentphase);
                   8416:     }
1.447     foxr     8417: 
1.157     albertel 8418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8419: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8420: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8421: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8422:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8423:3):                                                  $randompick,$sequence,\@master_seq,
                   8424:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8425:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8426: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8427: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8428: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8429:3): 				 $$scan_record{'scantron.doubleerror'},
                   8430:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8431:     	return (1,$currentphase);
                   8432:     }
                   8433:     return (0,$currentphase+1);
                   8434: }
                   8435: 
1.423     albertel 8436: 
1.503     raeburn  8437: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8438:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8439:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8440: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8441: 	&restore_bubble_lines();
1.257     albertel 8442: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8443:     }
1.330     albertel 8444: 
1.447     foxr     8445:     my (undef, undef, $sequence) =
1.257     albertel 8446: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8447: 
1.447     foxr     8448:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8449:     unless (ref($navmap)) {
                   8450:         if (ref($nav_error)) {
                   8451:             $$nav_error = 1;
                   8452:         }
1.591     raeburn  8453:         return;
1.582     raeburn  8454:     }
1.191     albertel 8455:     my $map=$navmap->getResourceByUrl($sequence);
                   8456:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8457:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8458: 
                   8459:     &Apache::lonxml::clear_problem_counter();
                   8460: 
1.557     raeburn  8461:     my $uname       = $env{'user.name'};
                   8462:     my $udom        = $env{'user.domain'};
1.435     foxr     8463:     my $cid         = $env{'request.course.id'};
                   8464:     my $total_lines = 0;
                   8465:     %bubble_lines_per_response = ();
1.447     foxr     8466:     %first_bubble_line         = ();
1.503     raeburn  8467:     %subdivided_bubble_lines   = ();
                   8468:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8469:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8470: 
1.447     foxr     8471:     my $response_number = 0;
                   8472:     my $bubble_line     = 0;
1.191     albertel 8473:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8474:3):         my $resid = $resource->id();
          (raeburn 8475:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8476:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8477:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8478: 	    foreach my $part_id (@{$parts}) {
                   8479:                 my $lines;
                   8480: 
                   8481: 	        # TODO - make this a persistent hash not an array.
                   8482: 
                   8483:                 # optionresponse, matchresponse and rankresponse type items 
                   8484:                 # render as separate sub-questions in exam mode.
                   8485:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8486:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8487:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8488:                     my ($numbub,$numshown);
                   8489:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8490:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8491:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8492:                         }
                   8493:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8494:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8495:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8496:                         }
                   8497:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8498:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8499:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8500:                         }
                   8501:                     }
                   8502:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8503:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8504:                     }
1.596.2.12.2.  (raeburn 8505:):                     my $bubbles_per_row =
                   8506:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8507:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8508:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8509:                         $inner_bubble_lines++;
                   8510:                     }
                   8511:                     for (my $i=0; $i<$numshown; $i++) {
                   8512:                         $subdivided_bubble_lines{$response_number} .= 
                   8513:                             $inner_bubble_lines.',';
                   8514:                     }
                   8515:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8516:                     $lines = $numshown * $inner_bubble_lines;
                   8517:                 } else {
                   8518:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8519:):                 }
1.542     raeburn  8520: 
                   8521:                 $first_bubble_line{$response_number} = $bubble_line;
                   8522: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8523:                 $responsetype_per_response{$response_number} = 
                   8524:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8525:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8526: 	        $response_number++;
                   8527: 
                   8528: 	        $bubble_line +=  $lines;
                   8529: 	        $total_lines +=  $lines;
                   8530: 	    }
                   8531:         }
                   8532:     }
1.552     raeburn  8533:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8534: 
                   8535:     &save_bubble_lines();
                   8536:     $env{'form.scantron_maxbubble'} =
                   8537: 	$total_lines;
                   8538:     return $env{'form.scantron_maxbubble'};
                   8539: }
1.523     raeburn  8540: 
1.596.2.12.2.  (raeburn 8541:): sub bubblesheet_bubbles_per_row {
                   8542:):     my ($scantron_config) = @_;
                   8543:):     my $bubbles_per_row;
                   8544:):     if (ref($scantron_config) eq 'HASH') {
                   8545:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8546:):     }
                   8547:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8548:):         $bubbles_per_row = 10;
                   8549:):     }
                   8550:):     return $bubbles_per_row;
                   8551:): }
                   8552:): 
1.157     albertel 8553: sub scantron_validate_missingbubbles {
                   8554:     my ($r,$currentphase) = @_;
                   8555:     #get student info
                   8556:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8557:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8558:3):     my (undef,undef,$sequence)=
                   8559:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8560: 
                   8561:     #get scantron line setup
1.596.2.12.2.  9(raebur 8562:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8563:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8564:3): 
                   8565:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8566:3):     unless (ref($navmap)) {
                   8567:3):         $r->print(&navmap_errormsg());
                   8568:3):         return(1,$currentphase);
                   8569:3):     }
                   8570:3): 
                   8571:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8572:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8573:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8574:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8575:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8576:3): 
1.582     raeburn  8577:     my $nav_error;
1.596.2.12.2.  6(raebur 8578:3):     if (ref($map)) {
                   8579:3):         $randomorder = $map->randomorder();
                   8580:3):         $randompick = $map->randompick();
          7(raebur 8581:3):         if ($randomorder || $randompick) {
                   8582:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8583:3):             if ($nav_error) {
                   8584:3):                 $r->print(&navmap_errormsg());
                   8585:3):                 return(1,$currentphase);
                   8586:3):             }
                   8587:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8588:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8589:3):         }
          6(raebur 8590:3):     } else {
                   8591:3):         $r->print(&navmap_errormsg());
          7(raebur 8592:3):         return(1,$currentphase);
          6(raebur 8593:3):     }
                   8594:3): 
                   8595:3): 
          (raeburn 8596:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8597:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8598:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8599:         return(1,$currentphase);
                   8600:     }
1.596.2.12.2.  6(raebur 8601:3): 
1.157     albertel 8602:     if (!$max_bubble) { $max_bubble=2**31; }
                   8603:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8604: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8605: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8606:3):         my $scan_record =
                   8607:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8608:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8609:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8610:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8611: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8612: 	my @to_correct;
1.470     foxr     8613: 	
                   8614: 	# Probably here's where the error is...
                   8615: 
1.157     albertel 8616: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8617:             my $lastbubble;
                   8618:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8619:3):                 my $question = $1;
                   8620:3):                 my $subquestion = $2;
                   8621:3):                 my ($first,$responsenum);
                   8622:3):                 if ($randomorder || $randompick) {
                   8623:3):                     $responsenum = $respnumlookup{$question-1};
                   8624:3):                     $first = $startline{$question-1};
                   8625:3):                 } else {
                   8626:3):                     $responsenum = $question-1;
                   8627:3):                     $first = $first_bubble_line{$responsenum};
                   8628:3):                 }
                   8629:3):                 if (!defined($first)) { next; }
          7(raebur 8630:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8631:3):                 my $subcount = 1;
                   8632:3):                 while ($subcount<$subquestion) {
                   8633:3):                     $first += $subans[$subcount-1];
                   8634:3):                     $subcount ++;
                   8635:3):                 }
                   8636:3):                 my $count = $subans[$subquestion-1];
                   8637:3):                 $lastbubble = $first + $count;
1.505     raeburn  8638:             } else {
1.596.2.12.2.  6(raebur 8639:3):                 my ($first,$responsenum);
                   8640:3):                 if ($randomorder || $randompick) {
                   8641:3):                     $responsenum = $respnumlookup{$missing-1};
                   8642:3):                     $first = $startline{$missing-1};
                   8643:3):                 } else {
                   8644:3):                     $responsenum = $missing-1;
                   8645:3):                     $first = $first_bubble_line{$responsenum};
                   8646:3):                 }
                   8647:3):                 if (!defined($first)) { next; }
                   8648:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8649:             }
                   8650:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8651: 	    push(@to_correct,$missing);
                   8652: 	}
                   8653: 	if (@to_correct) {
                   8654: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8655:3): 				     $line,'missingbubble',\@to_correct,
                   8656:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8657:3):                                      \%startline);
1.157     albertel 8658: 	    return (1,$currentphase);
                   8659: 	}
                   8660: 
                   8661:     }
                   8662:     return (0,$currentphase+1);
                   8663: }
                   8664: 
1.596.2.12.2.  (raeburn 8665:): sub hand_bubble_option {
                   8666:):     my (undef, undef, $sequence) =
                   8667:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8668:):     return if ($sequence eq '');
                   8669:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8670:):     unless (ref($navmap)) {
                   8671:):         return;
                   8672:):     }
                   8673:):     my $needs_hand_bubbles;
                   8674:):     my $map=$navmap->getResourceByUrl($sequence);
                   8675:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8676:):     foreach my $res (@resources) {
                   8677:):         if (ref($res)) {
                   8678:):             if ($res->is_problem()) {
                   8679:):                 my $partlist = $res->parts();
                   8680:):                 foreach my $part (@{ $partlist }) {
                   8681:):                     my @types = $res->responseType($part);
                   8682:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8683:):                         $needs_hand_bubbles = 1;
                   8684:):                         last;
                   8685:):                     }
                   8686:):                 }
                   8687:):             }
                   8688:):         }
                   8689:):     }
                   8690:):     if ($needs_hand_bubbles) {
          9(raebur 8691:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8692:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8693:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8694:):                &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 />').
                   8695:):                '<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 8696:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8697:):     }
                   8698:):     return;
                   8699:): }
1.423     albertel 8700: 
1.82      albertel 8701: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8702:0):     my ($r,$symb) = @_;
1.513     foxr     8703: 
1.257     albertel 8704:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8705:     if (!$symb) {
                   8706: 	return '';
                   8707:     }
1.324     albertel 8708:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8709: 
1.596.2.12.2.  9(raebur 8710:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8711:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8712:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8713:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8714:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8715:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8716:     unless (ref($navmap)) {
                   8717:         $r->print(&navmap_errormsg());
                   8718:         return '';
1.596.2.12.2.  6(raebur 8719:3):     }
1.83      albertel 8720:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8721:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8722:3):         %grader_randomlists_by_symb);
          1(raebur 8723:2):     if (ref($map)) {
                   8724:2):         $randomorder = $map->randomorder();
          6(raebur 8725:3):         $randompick = $map->randompick();
                   8726:3):     } else {
                   8727:3):         $r->print(&navmap_errormsg());
                   8728:3):         return '';
          1(raebur 8729:2):     }
          6(raebur 8730:3):     my $nav_error;
1.83      albertel 8731:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8732:3):     if ($randomorder || $randompick) {
                   8733:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8734:3):         if ($nav_error) {
                   8735:3):             $r->print(&navmap_errormsg());
                   8736:3):             return '';
1.586     raeburn  8737:         }
                   8738:     }
1.596.2.12.2.  6(raebur 8739:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8740:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8741: 
1.554     raeburn  8742:     my ($uname,$udom);
1.82      albertel 8743:     my $result= <<SCANTRONFORM;
1.81      albertel 8744: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8745:   <input type="hidden" name="command" value="scantron_configphase" />
                   8746:   $default_form_data
                   8747: SCANTRONFORM
1.82      albertel 8748:     $r->print($result);
                   8749: 
                   8750:     my @delayqueue;
1.542     raeburn  8751:     my (%completedstudents,%scandata);
1.140     albertel 8752:     
1.520     www      8753:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8754:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8755:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 8756:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8757:     $r->print('<br />');
1.140     albertel 8758:     my $start=&Time::HiRes::time();
1.158     albertel 8759:     my $i=-1;
1.542     raeburn  8760:     my $started;
1.447     foxr     8761: 
1.596.2.12.2.  (raeburn 8762:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8763:     if ($nav_error) {
                   8764:         $r->print(&navmap_errormsg());
                   8765:         return '';
                   8766:     }
                   8767: 
1.513     foxr     8768:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8769:     # the user and return.
                   8770: 
                   8771:     if ($ssi_error) {
                   8772: 	$r->print("</form>");
                   8773: 	&ssi_print_error($r);
1.520     www      8774:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8775: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8776:     }
1.447     foxr     8777: 
1.596.2.12.2.  9(raebur 8778:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8779:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8780:3):     my %orderedforcode;
1.542     raeburn  8781: 
1.157     albertel 8782:     while ($i<$scanlines->{'count'}) {
                   8783:  	($uname,$udom)=('','');
                   8784:  	$i++;
1.200     albertel 8785:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8786:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8787: 	if ($started) {
1.596.2.12.2.  1(raebur 8788:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8789: 	}
                   8790: 	$started=1;
1.596.2.12.2.  6(raebur 8791:3):         my %respnumlookup = ();
                   8792:3):         my %startline = ();
                   8793:3):         my $total;
1.157     albertel 8794:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8795:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8796:3):                                                  $randompick,$sequence,\@master_seq,
                   8797:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8798:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8799:3):                                                  \$total);
1.157     albertel 8800:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8801:  					      \%idmap,$i)) {
                   8802:   	    &scantron_add_delay(\@delayqueue,$line,
                   8803:  				'Unable to find a student that matches',1);
                   8804:  	    next;
                   8805:   	}
                   8806:  	if (exists $completedstudents{$uname}) {
                   8807:  	    &scantron_add_delay(\@delayqueue,$line,
                   8808:  				'Student '.$uname.' has multiple sheets',2);
                   8809:  	    next;
                   8810:  	}
1.596.2.12.2.  1(raebur 8811:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8812:2):         my $user = $uname.':'.$usec;
1.157     albertel 8813:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8814: 
1.596.2.12.2.  1(raebur 8815:2):         my $scancode;
                   8816:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8817:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8818:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8819:2):         } else {
                   8820:2):             $scancode = '';
                   8821:2):         }
                   8822:2): 
                   8823:2):         my @mapresources = @resources;
          6(raebur 8824:3):         if ($randomorder || $randompick) {
          1(raebur 8825:2):             @mapresources =
          6(raebur 8826:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8827:3):                              \%orderedforcode);
          1(raebur 8828:2):         }
1.586     raeburn  8829:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8830:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8831:             my $ressymb;
                   8832:             if (ref($resource)) {
                   8833:                 $ressymb = $resource->symb();
                   8834:             } else {
                   8835:                 $res_error = 1;
                   8836:                 last;
                   8837:             }
1.557     raeburn  8838:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8839:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8840:7):                 my $currcode;
                   8841:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8842:7):                     $currcode = $scancode;
                   8843:7):                 }
1.557     raeburn  8844:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8845:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8846:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8847:7):                                               $currcode);
1.557     raeburn  8848:                 $partids_by_symb{$ressymb} = $parts;
                   8849:             } else {
                   8850:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8851:             }
1.554     raeburn  8852:         }
                   8853: 
1.586     raeburn  8854:         if ($res_error) {
                   8855:             &scantron_add_delay(\@delayqueue,$line,
                   8856:                                 'An error occurred while grading student '.$uname,2);
                   8857:             next;
                   8858:         }
                   8859: 
1.330     albertel 8860: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8861:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8862: 
                   8863: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8864: 	    &scantron_putfile($scanlines,$scan_data);
                   8865: 	}
1.161     albertel 8866: 	
1.542     raeburn  8867:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8868:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8869:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8870:3):                                    \%respnumlookup,\%startline) 
                   8871:3):             eq 'ssi_error') {
1.542     raeburn  8872:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8873:             $r->print("</form>");
                   8874:             &ssi_print_error($r);
                   8875:             &Apache::lonnet::remove_lock($lock);
                   8876:             return '';      # Why return ''?  Beats me.
                   8877:         }
1.513     foxr     8878: 
1.596.2.12.2.  6(raebur 8879:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8880:3):             my $parmresult =
                   8881:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8882:3):                                                        '0_examcode',2,$scancode,
                   8883:3):                                                        'string_examcode',$uname,
                   8884:3):                                                        $udom);
                   8885:3):         }
1.140     albertel 8886: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8887:         if ($env{'form.verifyrecord'}) {
                   8888:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8889:3):             if ($randompick) {
                   8890:3):                 if ($total) {
                   8891:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8892:3):                 }
                   8893:3):             }
                   8894:3): 
1.542     raeburn  8895:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8896:             chomp($studentdata);
                   8897:             $studentdata =~ s/\r$//;
                   8898:             my $studentrecord = '';
                   8899:             my $counter = -1;
1.596.2.12.2.  1(raebur 8900:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8901:                 my $ressymb = $resource->symb();
1.542     raeburn  8902:                 ($counter,my $recording) =
                   8903:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8904:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8905:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8906:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8907:                 $studentrecord .= $recording;
                   8908:             }
                   8909:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8910:                 &Apache::lonxml::clear_problem_counter();
                   8911:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8912:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8913:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8914:3):                                            \%respnumlookup,\%startline)
                   8915:3):                     eq 'ssi_error') {
1.554     raeburn  8916:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8917:                     $r->print("</form>");
                   8918:                     &ssi_print_error($r);
                   8919:                     &Apache::lonnet::remove_lock($lock);
                   8920:                     delete($completedstudents{$uname});
                   8921:                     return '';
                   8922:                 }
1.542     raeburn  8923:                 $counter = -1;
                   8924:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8925:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8926:                     my $ressymb = $resource->symb();
1.542     raeburn  8927:                     ($counter,my $recording) =
                   8928:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8929:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8930:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8931:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8932:3):                                                  \%startline);
1.542     raeburn  8933:                     $studentrecord .= $recording;
                   8934:                 }
                   8935:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8936:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8937:                     if ($scancode eq '') {
1.596.2.6  raeburn  8938:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8939:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8940:                     } else {
1.596.2.6  raeburn  8941:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8942:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8943:                     }
                   8944:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8945:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8946:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8947:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8948:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8949:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8950:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8951:                               &Apache::loncommon::end_data_table_row().
                   8952:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8953:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8954:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8955:                               &Apache::loncommon::end_data_table_row().
                   8956:                               &Apache::loncommon::end_data_table().'</p>');
                   8957:                 } else {
                   8958:                     $r->print('<br /><span class="LC_warning">'.
                   8959:                              &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 />'.
                   8960:                              &mt("As a consequence, this user's submission history records two tries.").
                   8961:                                  '</span><br />');
                   8962:                 }
                   8963:             }
                   8964:         }
1.543     raeburn  8965:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8966:     } continue {
1.330     albertel 8967: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8968: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8969:     }
1.140     albertel 8970:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8971:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8972: #    my $lasttime = &Time::HiRes::time()-$start;
                   8973: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8974: 
1.200     albertel 8975:     $r->print("</form>");
1.157     albertel 8976:     return '';
1.75      albertel 8977: }
1.157     albertel 8978: 
1.557     raeburn  8979: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8980:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8981:):         $bubbles_per_row) = @_;
1.557     raeburn  8982:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8983:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8984:         foreach my $resource (@{$resources}) {
                   8985:             my $ressymb = $resource->symb();
                   8986:             my ($analysis,$parts) =
                   8987:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8988:):                                           $env{'user.name'},$env{'user.domain'},
                   8989:):                                           1,$bubbles_per_row);
1.557     raeburn  8990:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8991:             if (ref($analysis) eq 'HASH') {
                   8992:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8993:                     $grader_randomlists_by_symb->{$ressymb} =
                   8994:                         $analysis->{'parts_withrandomlist'};
                   8995:                 }
                   8996:             }
                   8997:         }
                   8998:     }
                   8999:     return;
                   9000: }
                   9001: 
1.596.2.12.2.  1(raebur 9002:2): =pod
                   9003:2): 
                   9004:2): =item users_order
                   9005:2): 
                   9006:2):   Returns array of resources in current map, ordered based on either CODE,
                   9007:2):   if this is a CODEd exam, or based on student's identity if this is a
                   9008:2):   "NAMEd" exam.
                   9009:2): 
          6(raebur 9010:3):   Should be used when randomorder and/or randompick applied when the 
                   9011:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9012:3):   for the version of the exam the student received.
          1(raebur 9013:2): 
                   9014:2): =cut
                   9015:2): 
                   9016:2): sub users_order  {
          6(raebur 9017:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9018:2):     my @mapresources;
          6(raebur 9019:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9020:2):         return @mapresources;
                   9021:2):     }
          6(raebur 9022:3):     if ($scancode) {
                   9023:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9024:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9025:3):         } else {
                   9026:3):             $env{'form.CODE'} = $scancode;
                   9027:3):             my $actual_seq =
                   9028:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9029:3):                                                                $master_seq,
                   9030:3):                                                                $user,$scancode,1);
                   9031:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9032:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9033:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9034:3):                     if (@mapresources > 0) {
                   9035:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9036:3):                     }
                   9037:3):                 }
                   9038:3):             }
                   9039:3):             delete($env{'form.CODE'});
          1(raebur 9040:2):         }
                   9041:2):     } else {
                   9042:2):         my $actual_seq =
                   9043:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9044:2):                                                            $master_seq,
          5(raebur 9045:3):                                                            $user,undef,1);
          1(raebur 9046:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9047:2):             @mapresources =
                   9048:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9049:2):         }
          6(raebur 9050:3):     }
                   9051:3):     return @mapresources;
          1(raebur 9052:2): }
                   9053:2): 
1.542     raeburn  9054: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9055:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9056:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9057:3):     my $uselookup = 0;
                   9058:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9059:3):         (ref($startline) eq 'HASH')) {
                   9060:3):         $uselookup = 1;
                   9061:3):     }
                   9062:3): 
1.554     raeburn  9063:     if (ref($resources) eq 'ARRAY') {
                   9064:         my $count = 0;
                   9065:         foreach my $resource (@{$resources}) {
                   9066:             my $ressymb = $resource->symb();
                   9067:             my %form = ('submitted'      => 'scantron',
                   9068:                         'grade_target'   => 'grade',
                   9069:                         'grade_username' => $uname,
                   9070:                         'grade_domain'   => $udom,
                   9071:                         'grade_courseid' => $env{'request.course.id'},
                   9072:                         'grade_symb'     => $ressymb,
                   9073:                         'CODE'           => $scancode
                   9074:                        );
1.596.2.12.2.  (raeburn 9075:):             if ($bubbles_per_row ne '') {
                   9076:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9077:):             }
                   9078:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9079:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9080:):             }
1.554     raeburn  9081:             if (ref($parts) eq 'HASH') {
                   9082:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9083:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9084:3):                         if ($uselookup) {
                   9085:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9086:3):                         } else {
                   9087:3):                             $form{'scantron_questnum_start.'.$part} =
                   9088:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9089:3):                         }
1.554     raeburn  9090:                         $count++;
                   9091:                     }
                   9092:                 }
                   9093:             }
                   9094:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9095:             return 'ssi_error' if ($ssi_error);
                   9096:             last if (&Apache::loncommon::connection_aborted($r));
                   9097:         }
1.542     raeburn  9098:     }
                   9099:     return;
                   9100: }
                   9101: 
1.157     albertel 9102: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9103:0):     my ($r,$symb) = @_;
1.565     raeburn  9104:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9105:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9106:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9107:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9108:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9109: 							  'domainid',
1.565     raeburn  9110: 							  'coursename',$dom);
                   9111:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9112:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9113:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9114:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9115:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9116:     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 9117:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9118:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9119:     function checkUpload(formname) {
                   9120: 	if (formname.upfile.value == "") {
1.579     raeburn  9121: 	    alert("'.$nofile_alert.'");
1.157     albertel 9122: 	    return false;
                   9123: 	}
1.565     raeburn  9124:         if (formname.courseid.value == "") {
1.579     raeburn  9125:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9126:             return false;
                   9127:         }
1.157     albertel 9128: 	formname.submit();
                   9129:     }
1.565     raeburn  9130: 
                   9131:     function ToSyllabus() {
                   9132:         var cdom = '."'$dom'".';
                   9133:         var cnum = document.rules.courseid.value;
                   9134:         if (cdom == "" || cdom == null) {
                   9135:             return;
                   9136:         }
                   9137:         if (cnum == "" || cnum == null) {
                   9138:            return;
                   9139:         }
                   9140:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9141:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9142:         return;
                   9143:     }
                   9144: 
1.596.2.12.2.  9(raebur 9145:9):     '.$formatjs.'
                   9146:9): '));
                   9147:9):     $r->print('
1.596.2.4  raeburn  9148: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9149: 
1.492     albertel 9150: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9151: '.$default_form_data.
                   9152:   &Apache::lonhtmlcommon::start_pick_box().
                   9153:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9154:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9155:   &Apache::lonhtmlcommon::row_closure().
                   9156:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9157:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9158:   &Apache::lonhtmlcommon::row_closure().
                   9159:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9160:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9161:9):   &Apache::lonhtmlcommon::row_closure());
                   9162:9):     if ($formatoptions) {
                   9163:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9164:9):                   &Apache::lonhtmlcommon::row_closure());
                   9165:9):     }
                   9166:9):     $r->print(
1.565     raeburn  9167:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9168:   '<input type="file" name="upfile" size="50" />'.
                   9169:   &Apache::lonhtmlcommon::row_closure(1).
                   9170:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9171: 
1.492     albertel 9172: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9173: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9174: </form>
1.492     albertel 9175: ');
1.157     albertel 9176:     return '';
                   9177: }
                   9178: 
1.596.2.12.2.  9(raebur 9179:9): sub scantron_upload_dataformat {
                   9180:9):     my ($dom) = @_;
                   9181:9):     my ($formatoptions,$formattitle,$formatjs);
                   9182:9):     $formatjs = <<'END';
                   9183:9): function toggleScantab(form) {
                   9184:9):    return;
                   9185:9): }
                   9186:9): END
                   9187:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9188:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9189:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9190:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9191:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9192:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9193:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9194:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9195:9):                             my ($onclick,$formatextra,$singleline);
                   9196:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9197:9):                             my $count = 0;
                   9198:9):                             foreach my $line (@lines) {
                   9199:9):                                 next if ($line =~ /^#/);
                   9200:9):                                 $singleline = $line;
                   9201:9):                                 $count ++;
                   9202:9):                             }
                   9203:9):                             if ($count > 1) {
                   9204:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9205:9):                                                '<span class="LC_nobreak">'.
                   9206:9):                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9207:9):                                                &scantron_scantab().'</span></div>';
                   9208:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9209:9):                                 $formatjs = <<"END";
                   9210:9): function toggleScantab(form) {
                   9211:9):     var divid = 'bubbletype';
                   9212:9):     if (document.getElementById(divid)) {
                   9213:9):         var radioname = 'fileformat';
                   9214:9):         var num = form.elements[radioname].length;
                   9215:9):         if (num) {
                   9216:9):             for (var i=0; i<num; i++) {
                   9217:9):                 if (form.elements[radioname][i].checked) {
                   9218:9):                     var chosen = form.elements[radioname][i].value;
                   9219:9):                     if (chosen == 'dat') {
                   9220:9):                         document.getElementById(divid).style.display = 'none';
                   9221:9):                     } else if (chosen == 'csv') {
                   9222:9):                         document.getElementById(divid).style.display = 'block';
                   9223:9):                     }
                   9224:9):                 }
                   9225:9):             }
                   9226:9):         }
                   9227:9):     }
                   9228:9):     return;
                   9229:9): }
                   9230:9): 
                   9231:9): END
                   9232:9):                             } elsif ($count == 1) {
                   9233:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9234:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9235:9):                             }
                   9236:9):                             $formattitle = &mt('File format');
                   9237:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9238:9):                                              &mt('Plain Text (no delimiters)').
                   9239:9):                                              '</label>'.('&nbsp;'x2).
                   9240:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9241:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9242:9):                         }
                   9243:9):                     }
                   9244:9):                 }
                   9245:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9246:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9247:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9248:9):                         $formattitle = &mt('Bubblesheet type');
                   9249:9):                         $formatoptions = &scantron_scantab();
                   9250:9):                     }
                   9251:9):                 }
                   9252:9):             }
                   9253:9):         }
                   9254:9):     }
                   9255:9):     return ($formatoptions,$formattitle,$formatjs);
                   9256:9): }
1.423     albertel 9257: 
1.157     albertel 9258: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9259:0):     my ($r,$symb) = @_;
1.182     albertel 9260:     my $doanotherupload=
                   9261: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9262: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9263: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9264: 	'</form>'."\n";
1.257     albertel 9265:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9266: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9267: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9268: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9269:0):         unless ($symb) {
1.182     albertel 9270: 	    $r->print($doanotherupload);
                   9271: 	}
1.162     albertel 9272: 	return '';
                   9273:     }
1.257     albertel 9274:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9275:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9276:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9277:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9278:3):         $r->print(
                   9279:3):             &Apache::lonhtmlcommon::confirm_success(
                   9280:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9281:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9282:     } else {
1.596.2.12.2.  9(raebur 9283:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9284:9):         my $parser;
                   9285:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9286:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9287:9):                 my $is_csv;
                   9288:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9289:9):                 if (@possibles > 1) {
                   9290:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9291:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9292:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9293:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9294:9):                                     $is_csv = 1;
                   9295:9):                                 }
                   9296:9):                             }
                   9297:9):                         }
                   9298:9):                     }
                   9299:9):                 } elsif (@possibles == 1) {
                   9300:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9301:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9302:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9303:9):                                 $is_csv = 1;
                   9304:9):                             }
                   9305:9):                         }
                   9306:9):                     }
                   9307:9):                 }
                   9308:9):                 if ($is_csv) {
                   9309:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9310:9):                 }
                   9311:9):             }
                   9312:9):         }
                   9313:9):         my $result =
                   9314:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9315:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9316: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9317:3):             $r->print(
                   9318:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9319:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9320:3):                         (length($env{'form.upfile'})-1),
                   9321:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9322:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9323:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9324:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9325: 	} else {
1.596.2.12.2.  5(raebur 9326:3):             $r->print(
                   9327:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9328:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9329:3):                           $result,
1.568     raeburn  9330: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9331: 	}
                   9332:     }
1.174     albertel 9333:     if ($symb) {
1.596.2.12.2.  1(raebur 9334:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9335:     } else {
1.182     albertel 9336: 	$r->print($doanotherupload);
1.174     albertel 9337:     }
1.157     albertel 9338:     return '';
                   9339: }
                   9340: 
1.567     raeburn  9341: sub validate_uploaded_scantron_file {
                   9342:     my ($cdom,$cname,$fname) = @_;
                   9343:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9344:     my @lines;
                   9345:     if ($scanlines ne '-1') {
                   9346:         @lines=split("\n",$scanlines,-1);
                   9347:     }
                   9348:     my $output;
                   9349:     if (@lines) {
                   9350:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9351:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9352:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9353:         my %idmap = &username_to_idmap($classlist);
                   9354:         foreach my $key (keys(%idmap)) {
                   9355:             my $lckey = lc($key);
                   9356:             $idmap{$lckey} = $idmap{$key};
                   9357:         }
                   9358:         my %unique_formats;
1.596.2.12.2.  9(raebur 9359:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9360:         foreach my $line (@formatlines) {
                   9361:             chomp($line);
                   9362:             my @config = split(/:/,$line);
                   9363:             my $idstart = $config[5];
                   9364:             my $idlength = $config[6];
                   9365:             if (($idstart ne '') && ($idlength > 0)) {
                   9366:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9367:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9368:                 } else {
                   9369:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9370:                 }
                   9371:             }
                   9372:         }
                   9373:         foreach my $key (keys(%unique_formats)) {
                   9374:             my ($idstart,$idlength) = split(':',$key);
                   9375:             %{$counts{$key}} = (
                   9376:                                'found'   => 0,
                   9377:                                'total'   => 0,
                   9378:                               );
                   9379:             foreach my $line (@lines) {
                   9380:                 next if ($line =~ /^#/);
                   9381:                 next if ($line =~ /^[\s\cz]*$/);
                   9382:                 my $id = substr($line,$idstart-1,$idlength);
                   9383:                 $id = lc($id);
                   9384:                 if (exists($idmap{$id})) {
                   9385:                     $counts{$key}{'found'} ++;
                   9386:                 }
                   9387:                 $counts{$key}{'total'} ++;
                   9388:             }
                   9389:             if ($counts{$key}{'total'}) {
                   9390:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9391:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9392:                     $max_match_pct = $percent_match;
                   9393:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9394:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9395:                     $max_match_count = $counts{$key}{'total'};
                   9396:                 }
                   9397:             }
                   9398:         }
                   9399:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9400:             my $format_descs;
                   9401:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9402:             for (my $i=0; $i<$numwithformat; $i++) {
                   9403:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9404:                 if ($i<$numwithformat-2) {
                   9405:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9406:                 } elsif ($i==$numwithformat-2) {
                   9407:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9408:                 } elsif ($i==$numwithformat-1) {
                   9409:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9410:                 }
                   9411:             }
                   9412:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9413:3):             $output .= '<br />';
                   9414:3):             if ($found_match_count == $max_match_count) {
                   9415:3):                 # 100% matching entries
                   9416:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9417:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9418:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9419:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9420:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9421:3):                     ' in the file (for the format defined for [_3]).',
                   9422:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9423:3):             } else {
                   9424:3):                 # Not all entries matching? -> Show warning and additional info
                   9425:3):                 $output .=
                   9426:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9427:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9428:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9429:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9430:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9431:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9432:3):                         ' in the file (for the format defined for [_3]).',
                   9433:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9434:3):                     '<p class="LC_info">'.
                   9435:3):                     &mt('A low percentage of matches results from one of the following:').
                   9436:3):                     '</p><ul>'.
                   9437:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9438:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9439:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9440:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9441:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9442:3):                     '</ul>';
                   9443:3):             }
1.567     raeburn  9444:         }
                   9445:     } else {
1.596.2.12.2.  5(raebur 9446:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9447:     }
                   9448:     return $output;
                   9449: }
                   9450: 
1.202     albertel 9451: sub valid_file {
                   9452:     my ($requested_file)=@_;
                   9453:     foreach my $filename (sort(&scantron_filenames())) {
                   9454: 	if ($requested_file eq $filename) { return 1; }
                   9455:     }
                   9456:     return 0;
                   9457: }
                   9458: 
                   9459: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9460:0):     my ($r,$symb) = @_;
          (raeburn 9461:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9462:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9463:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9464:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9465:     if (! &valid_file($file)) {
1.492     albertel 9466: 	$r->print('
1.202     albertel 9467: 	<p>
1.596.2.12.2.  3(raebur 9468:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9469:         </p>
1.492     albertel 9470: ');
1.202     albertel 9471: 	return;
                   9472:     }
                   9473:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9474:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9475:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9476:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9477:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9478:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9479:     $r->print('
1.202     albertel 9480:     <p>
1.596.2.12.2.  1(raebur 9481:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9482: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9483:     </p>
                   9484:     <p>
1.492     albertel 9485: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9486: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9487:     </p>
                   9488:     <p>
1.492     albertel 9489: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9490: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9491:     </p>
1.492     albertel 9492: ');
1.202     albertel 9493:     return '';
                   9494: }
1.157     albertel 9495: 
1.523     raeburn  9496: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9497:0):     my ($r,$symb) = @_;
1.523     raeburn  9498:     if (!$symb) {return '';}
                   9499:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9500:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9501:     my $numletts = scalar(keys(%lettdig));
                   9502:     my $cnum = $env{'course.'.$cid.'.num'};
                   9503:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9504:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9505:     my %record;
                   9506:     my %scantron_config =
1.596.2.12.2.  9(raebur 9507:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9508:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9509:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9510:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9511:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9512:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9513:     unless (ref($navmap)) {
                   9514:         $r->print(&navmap_errormsg());
                   9515:         return '';
                   9516:     }
1.523     raeburn  9517:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9518:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9519:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9520:2):     if (ref($map)) {
                   9521:2):         $randomorder=$map->randomorder();
          7(raebur 9522:3):         $randompick=$map->randompick();
          1(raebur 9523:2):     }
1.557     raeburn  9524:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9525:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9526:3):     if ($nav_error) {
                   9527:3):         $r->print(&navmap_errormsg());
                   9528:3):         return '';
          1(raebur 9529:2):     }
          (raeburn 9530:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9531:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9532:     my ($uname,$udom);
1.523     raeburn  9533:     my (%scandata,%lastname,%bylast);
                   9534:     $r->print('
                   9535: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9536: 
                   9537:     my @delayqueue;
                   9538:     my %completedstudents;
                   9539: 
1.596.2.12.2.  6(raebur 9540:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9541:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9542:3):     my ($username,$domain,$started);
          (raeburn 9543:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9544:     if ($nav_error) {
                   9545:         $r->print(&navmap_errormsg());
                   9546:         return '';
                   9547:     }
1.523     raeburn  9548: 
                   9549:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9550:                                           'Processing first student');
                   9551:     my $start=&Time::HiRes::time();
                   9552:     my $i=-1;
                   9553: 
                   9554:     while ($i<$scanlines->{'count'}) {
                   9555:         ($username,$domain,$uname)=('','','');
                   9556:         $i++;
                   9557:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9558:         if ($line=~/^[\s\cz]*$/) { next; }
                   9559:         if ($started) {
                   9560:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9561:                                                      'last student');
                   9562:         }
                   9563:         $started=1;
                   9564:         my $scan_record=
                   9565:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9566:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9567:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9568:3):                                               \%idmap,$i)) {
1.523     raeburn  9569:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9570:                                 'Unable to find a student that matches',1);
                   9571:             next;
                   9572:         }
                   9573:         if (exists $completedstudents{$uname}) {
                   9574:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9575:                                 'Student '.$uname.' has multiple sheets',2);
                   9576:             next;
                   9577:         }
                   9578:         my $pid = $scan_record->{'scantron.ID'};
                   9579:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9580:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9581:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9582:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9583:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9584:2): 
                   9585:2):         my $scancode;
                   9586:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9587:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9588:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9589:2):         } else {
                   9590:2):             $scancode = '';
                   9591:2):         }
                   9592:2): 
                   9593:2):         my @mapresources = @resources;
          6(raebur 9594:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9595:3):         my %respnumlookup=();
                   9596:3):         my %startline=();
                   9597:3):         if ($randomorder || $randompick) {
          1(raebur 9598:2):             @mapresources =
          6(raebur 9599:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9600:3):                              \%orderedforcode);
                   9601:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9602:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9603:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9604:3):                                              \%respnumlookup,\%startline);
                   9605:3):             if ($randompick && $total) {
                   9606:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9607:3):             }
          1(raebur 9608:2):         }
          6(raebur 9609:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9610:3):         chomp($scandata{$pid});
                   9611:3):         $scandata{$pid} =~ s/\r$//;
                   9612:3): 
1.523     raeburn  9613:         my $counter = -1;
1.596.2.12.2.  1(raebur 9614:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9615:             my $parts;
1.554     raeburn  9616:             my $ressymb = $resource->symb();
1.557     raeburn  9617:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9618:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9619:7):                 my $currcode;
                   9620:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9621:7):                     $currcode = $scancode;
                   9622:7):                 }
1.557     raeburn  9623:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9624:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9625:):                                               $username,$domain,undef,
          1(raebur 9626:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9627:             } else {
                   9628:                 $parts = $grader_partids_by_symb{$ressymb};
                   9629:             }
1.542     raeburn  9630:             ($counter,my $recording) =
                   9631:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9632:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9633:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9634:3):                                          $randomorder,$randompick,
                   9635:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9636:             $record{$pid} .= $recording;
1.523     raeburn  9637:         }
                   9638:     }
                   9639:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9640:     $r->print('<br />');
                   9641:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9642:     $passed = 0;
                   9643:     $failed = 0;
                   9644:     $numstudents = 0;
                   9645:     foreach my $last (sort(keys(%bylast))) {
                   9646:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9647:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9648:                 my $showscandata = $scandata{$pid};
                   9649:                 my $showrecord = $record{$pid};
                   9650:                 $showscandata =~ s/\s/&nbsp;/g;
                   9651:                 $showrecord =~ s/\s/&nbsp;/g;
                   9652:                 if ($scandata{$pid} eq $record{$pid}) {
                   9653:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9654:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9655: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9656: '</tr>'."\n".
                   9657: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9658:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9659:                     $passed ++;
                   9660:                 } else {
                   9661:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9662:                     $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  9663: '</tr>'."\n".
                   9664: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9665:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9666: '</tr>'."\n";
                   9667:                     $failed ++;
                   9668:                 }
                   9669:                 $numstudents ++;
                   9670:             }
                   9671:         }
                   9672:     }
1.596.2.4  raeburn  9673:     $r->print('<p>'.
1.596.2.8  raeburn  9674:               &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  9675:                   '<b>',
                   9676:                   $numstudents,
                   9677:                   '</b>',
                   9678:                   $env{'form.scantron_maxbubble'}).
                   9679:               '</p>'
                   9680:     );
1.596.2.12.2.  2(raebur 9681:2):     $r->print('<p>'
                   9682:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9683:2):              .'<br />'
                   9684:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9685:2):              .'</p>');
1.523     raeburn  9686:     if ($passed) {
1.572     www      9687:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9688:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9689:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9690:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9691:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9692:                  $okstudents."\n".
                   9693:                  &Apache::loncommon::end_data_table().'<br />');
                   9694:     }
                   9695:     if ($failed) {
1.572     www      9696:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9697:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9698:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9699:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9700:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9701:                  $badstudents."\n".
                   9702:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9703:                  &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  9704:     }
1.596.2.12.2.  1(raebur 9705:0):     $r->print('</form><br />');
1.523     raeburn  9706:     return;
                   9707: }
                   9708: 
1.542     raeburn  9709: sub verify_scantron_grading {
1.554     raeburn  9710:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9711:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9712:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9713:     my ($record,%expected,%startpos);
                   9714:     return ($counter,$record) if (!ref($resource));
                   9715:     return ($counter,$record) if (!$resource->is_problem());
                   9716:     my $symb = $resource->symb();
1.554     raeburn  9717:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9718:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9719:         $counter ++;
                   9720:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9721:3):         my $respnum = $counter;
                   9722:3):         if ($randomorder || $randompick) {
                   9723:3):             $respnum = $respnumlookup->{$counter};
                   9724:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9725:3):         } else {
                   9726:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9727:3):         }
                   9728:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9729:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9730:             foreach my $item (@sub_lines) {
                   9731:                 $expected{$part_id} += $item;
                   9732:             }
                   9733:         } else {
1.596.2.12.2.  6(raebur 9734:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9735:         }
                   9736:     }
                   9737:     if ($symb) {
                   9738:         my %recorded;
                   9739:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9740:         if ($returnhash{'version'}) {
                   9741:             my %lasthash=();
                   9742:             my $version;
                   9743:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9744:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9745:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9746:                 }
                   9747:             }
                   9748:             foreach my $key (keys(%lasthash)) {
                   9749:                 if ($key =~ /\.scantron$/) {
                   9750:                     my $value = &unescape($lasthash{$key});
                   9751:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9752:                     if ($value eq '') {
                   9753:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9754:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9755:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9756:                             }
                   9757:                         }
                   9758:                     } else {
                   9759:                         my @tocheck;
                   9760:                         my @items = split(//,$value);
                   9761:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9762:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9763:                             if (@items < $expected{$part_id}) {
                   9764:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9765:                                 my @singles = split(//,$fragment);
                   9766:                                 foreach my $pos (@singles) {
                   9767:                                     if ($pos eq ' ') {
                   9768:                                         push(@tocheck,$pos);
                   9769:                                     } else {
                   9770:                                         my $next = shift(@items);
                   9771:                                         push(@tocheck,$next);
                   9772:                                     }
                   9773:                                 }
                   9774:                             } else {
                   9775:                                 @tocheck = @items;
                   9776:                             }
                   9777:                             foreach my $letter (@tocheck) {
                   9778:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9779:                                     if ($letter !~ /^[A-J]$/) {
                   9780:                                         $letter = $scantron_config->{'Qoff'};
                   9781:                                     }
                   9782:                                     $recorded{$part_id} .= $letter;
                   9783:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9784:                                     my $digit;
                   9785:                                     if ($letter !~ /^[A-J]$/) {
                   9786:                                         $digit = $scantron_config->{'Qoff'};
                   9787:                                     } else {
                   9788:                                         $digit = $lettdig->{$letter};
                   9789:                                     }
                   9790:                                     $recorded{$part_id} .= $digit;
                   9791:                                 }
                   9792:                             }
                   9793:                         } else {
                   9794:                             @tocheck = @items;
                   9795:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9796:                                 my $curr_sub = shift(@tocheck);
                   9797:                                 my $digit;
                   9798:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9799:                                     $digit = $lettdig->{$curr_sub}-1;
                   9800:                                 }
                   9801:                                 if ($curr_sub eq 'J') {
                   9802:                                     $digit += scalar($numletts);
                   9803:                                 }
                   9804:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9805:                                     if ($j == $digit) {
                   9806:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9807:                                     } else {
                   9808:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9809:                                     }
                   9810:                                 }
                   9811:                             }
                   9812:                         }
                   9813:                     }
                   9814:                 }
                   9815:             }
                   9816:         }
1.554     raeburn  9817:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9818:             if ($recorded{$part_id} eq '') {
                   9819:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9820:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9821:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9822:                     }
                   9823:                 }
                   9824:             }
                   9825:             $record .= $recorded{$part_id};
                   9826:         }
                   9827:     }
                   9828:     return ($counter,$record);
                   9829: }
                   9830: 
1.75      albertel 9831: #-------- end of section for handling grading scantron forms -------
                   9832: #
                   9833: #-------------------------------------------------------------------
                   9834: 
1.72      ng       9835: #-------------------------- Menu interface -------------------------
                   9836: #
1.596.2.12.2.  (raeburn 9837:): #--- Href with symb and command ---
                   9838:): 
                   9839:): sub href_symb_cmd {
                   9840:):     my ($symb,$cmd)=@_;
                   9841:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9842:): }
                   9843:): 
1.443     banghart 9844: sub grading_menu {
1.596.2.12.2.  1(raebur 9845:0):     my ($request,$symb) = @_;
1.443     banghart 9846:     if (!$symb) {return '';}
                   9847: 
                   9848:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 9849:0):                   'command'=>'individual');
                   9850:0): 
                   9851:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9852:0): 
                   9853:0):     $fields{'command'}='ungraded';
                   9854:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9855:0): 
                   9856:0):     $fields{'command'}='table';
                   9857:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9858:0): 
                   9859:0):     $fields{'command'}='all_for_one';
                   9860:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9861:0): 
                   9862:0):     $fields{'command'}='downloadfilesselect';
                   9863:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9864:     
1.443     banghart 9865:     $fields{'command'} = 'csvform';
1.538     schulted 9866:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9867:     
1.443     banghart 9868:     $fields{'command'} = 'processclicker';
1.538     schulted 9869:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9870:     
1.443     banghart 9871:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9872:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 9873:0): 
                   9874:0):     $fields{'command'} = 'initialverifyreceipt';
                   9875:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9876:     
1.596.2.12.2.  1(raebur 9877:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9878:             items =>[
1.596.2.12.2.  1(raebur 9879:0):                         {       linktext => 'Select individual students to grade',
                   9880:0):                                 url => $url1a,
                   9881:0):                                 permission => 'F',
                   9882:0):                                 icon => 'grade_students.png',
                   9883:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   9884:0):                         },
                   9885:0):                         {       linktext => 'Grade ungraded submissions',
                   9886:0):                                 url => $url1b,
                   9887:0):                                 permission => 'F',
                   9888:0):                                 icon => 'ungrade_sub.png',
                   9889:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   9890:0):                         },
                   9891:0): 
                   9892:0):                         {       linktext => 'Grading table',
                   9893:0):                                 url => $url1c,
                   9894:0):                                 permission => 'F',
                   9895:0):                                 icon => 'grading_table.png',
                   9896:0):                                 linktitle => 'Grade current resource for all students.'
                   9897:0):                         },
                   9898:0):                         {       linktext => 'Grade page/folder for one student',
                   9899:0):                                 url => $url1d,
                   9900:0):                                 permission => 'F',
                   9901:0):                                 icon => 'grade_PageFolder.png',
                   9902:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 9903:                         },
1.596.2.12.2.  3(raebur 9904:0):                         {       linktext => 'Download submitted files',
          1(raebur 9905:0):                                 url => $url1e,
                   9906:0):                                 permission => 'F',
                   9907:0):                                 icon => 'download_sub.png',
          3(raebur 9908:0):                                 linktitle => 'Download all files submitted by students.'
          1(raebur 9909:0):                         }]},
                   9910:0):                          { categorytitle=>'Automated Grading',
                   9911:0):                items =>[
                   9912:0): 
1.538     schulted 9913:                 	    {	linktext => 'Upload Scores',
                   9914:                     		url => $url2,
                   9915:                     		permission => 'F',
                   9916:                     		icon => 'uploadscores.png',
                   9917:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9918:                 	    },
                   9919:                 	    {	linktext => 'Process Clicker',
                   9920:                     		url => $url3,
                   9921:                     		permission => 'F',
                   9922:                     		icon => 'addClickerInfoFile.png',
                   9923:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9924:                 	    },
1.587     raeburn  9925:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9926:                     		url => $url4,
                   9927:                     		permission => 'F',
1.596.2.12.2.  1(raebur 9928:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  9929:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 9930:0):                 	    },
                   9931:0):                             {   linktext => 'Verify Receipt Number',
                   9932:0):                                 url => $url5,
                   9933:0):                                 permission => 'F',
                   9934:0):                                 icon => 'receipt_number.png',
                   9935:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9936:0):                             }
                   9937:0): 
1.538     schulted 9938:                     ]
                   9939:             });
                   9940: 
1.443     banghart 9941:     # Create the menu
                   9942:     my $Str;
1.445     banghart 9943:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9944:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 9945:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 9946: 
1.596.2.12.2.  1(raebur 9947:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9948:     return $Str;    
                   9949: }
                   9950: 
1.596.2.12.2.  1(raebur 9951:0): sub ungraded {
                   9952:0):     my ($request)=@_;
                   9953:0):     &submit_options($request);
                   9954:0): }
1.443     banghart 9955: 
1.596.2.12.2.  1(raebur 9956:0): sub submit_options_sequence {
                   9957:0):     my ($request,$symb) = @_;
1.72      ng       9958:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 9959:0):     &commonJSfunctions($request);
                   9960:0):     my $result;
1.72      ng       9961: 
1.596.2.12.2.  1(raebur 9962:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9963:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9964:0):     $result.=&selectfield(0).
                   9965:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   9966:0):             <div>
                   9967:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9968:0):             </div>
                   9969:0):         </div>
                   9970:0):   </form>';
                   9971:0):     return $result;
                   9972:0): }
                   9973:0): 
                   9974:0): sub submit_options_table {
                   9975:0):     my ($request,$symb) = @_;
                   9976:0):     if (!$symb) {return '';}
1.118     ng       9977:     &commonJSfunctions($request);
1.473     albertel 9978:     my $result;
1.596.2.12.2.  1(raebur 9979:0): 
                   9980:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9981:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9982:0): 
                   9983:0):     $result.=&selectfield(1).
                   9984:0):             '<input type="hidden" name="command" value="viewgrades" />
                   9985:0):             <div>
                   9986:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9987:0):             </div>
                   9988:0):         </div>
                   9989:0):   </form>';
                   9990:0):     return $result;
                   9991:0): }
                   9992:0): 
                   9993:0): sub submit_options_download {
                   9994:0):     my ($request,$symb) = @_;
                   9995:0):     if (!$symb) {return '';}
                   9996:0): 
                   9997:0):     my $res_error;
                   9998:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   9999:0):         &response_type($symb,\$res_error);
                   10000:0):     if ($res_error) {
                   10001:0):         $request->print(&mt('An error occurred retrieving response types'));
                   10002:0):         return;
                   10003:0):     }
                   10004:0):     unless ($numessay) {
                   10005:0):         $request->print(&mt('No essayresponse items found'));
                   10006:0):         return;
                   10007:0):     }
                   10008:0):     my $table;
                   10009:0):     if (ref($partlist) eq 'ARRAY') {
                   10010:0):         if (scalar(@$partlist) > 1 ) {
                   10011:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10012:         }
                   10013:     }
                   10014: 
1.596.2.12.2.  1(raebur 10015:0):     &commonJSfunctions($request);
1.72      ng       10016: 
1.596.2.12.2.  1(raebur 10017:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10018:0):         $table."\n".
                   10019:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10020:     $result.='
1.533     bisitz   10021: <h2>
1.596.2.12.2.  3(raebur 10022:0):   '.&mt('Select Students for whom to Download Submitted Files').'
          1(raebur 10023:0): </h2>'.&selectfield(1).'
                   10024:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10025:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10026:0):             </div>
                   10027:0):           </div>
                   10028:0): 
                   10029:0): 
                   10030:0):   </form>';
                   10031:0):     return $result;
                   10032:0): }
                   10033:0): 
                   10034:0): #--- Displays the submissions first page -------
                   10035:0): sub submit_options {
                   10036:0):     my ($request,$symb) = @_;
                   10037:0):     if (!$symb) {return '';}
                   10038:0): 
                   10039:0):     &commonJSfunctions($request);
                   10040:0):     my $result;
                   10041:0): 
                   10042:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10043:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10044:0):     $result.=&selectfield(1).'
                   10045:0):                 <input type="hidden" name="command" value="submission" />
                   10046:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10047:0):             </div>
                   10048:0):           </div>
                   10049:0):   </form>';
                   10050:0):     return $result;
                   10051:0): }
                   10052:0): 
                   10053:0): sub selectfield {
                   10054:0):    my ($full)=@_;
                   10055:0):    my %options =
                   10056:0):        (&substatus_options,
                   10057:0):         'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10058:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10059: 
                   10060:     <fieldset>
                   10061:       <legend>
                   10062:        '.&mt('Sections').'
                   10063:       </legend>
1.596.2.12.2.  1(raebur 10064:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10065:     </fieldset>
1.596.2.12.2.  1(raebur 10066:0): 
1.533     bisitz   10067:     <fieldset>
                   10068:       <legend>
                   10069:         '.&mt('Groups').'
                   10070:       </legend>
                   10071:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10072:     </fieldset>
1.596.2.12.2.  1(raebur 10073:0):  
1.533     bisitz   10074:     <fieldset>
                   10075:       <legend>
                   10076:         '.&mt('Access Status').'
                   10077:       </legend>
1.596.2.12.2.  1(raebur 10078:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10079:0):     </fieldset>';
                   10080:0):     if ($full) {
                   10081:0):         $result.='
1.533     bisitz   10082:     <fieldset>
                   10083:       <legend>
                   10084:         '.&mt('Submission Status').'
1.596.2.12.2.  1(raebur 10085:0):       </legend>'.
                   10086:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10087:0):    '</fieldset>';
                   10088:0):     }
                   10089:0):     $result.='</div><br />';
1.44      ng       10090:     return $result;
1.2       albertel 10091: }
                   10092: 
1.596.2.12.2.  7(raebur 10093:6): sub substatus_options {
                   10094:6):     return &Apache::lonlocal::texthash(
                   10095:6):                                       'yes'       => 'with submissions',
                   10096:6):                                       'queued'    => 'in grading queue',
                   10097:6):                                       'graded'    => 'with ungraded submissions',
                   10098:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10099:7):                                       'all'       => 'with any status',
                   10100:7):                                       );
          7(raebur 10101:6): }
                   10102:6): 
          1(raebur 10103:0): sub transtatus_options {
                   10104:0):     return &Apache::lonlocal::texthash(
                   10105:0):                                        'yes'       => 'with score transactions',
                   10106:0):                                        'incorrect' => 'with less than full credit',
                   10107:0):                                        'all'       => 'with any status',
                   10108:0):                                       );
                   10109:0): }
                   10110:0): 
1.285     albertel 10111: sub reset_perm {
                   10112:     undef(%perm);
                   10113: }
                   10114: 
                   10115: sub init_perm {
                   10116:     &reset_perm();
1.300     albertel 10117:     foreach my $test_perm ('vgr','mgr','opa') {
                   10118: 
                   10119: 	my $scope = $env{'request.course.id'};
                   10120: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10121: 
                   10122: 	    $scope .= '/'.$env{'request.course.sec'};
                   10123: 	    if ( $perm{$test_perm}=
                   10124: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10125: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10126: 	    } else {
                   10127: 		delete($perm{$test_perm});
                   10128: 	    }
1.285     albertel 10129: 	}
                   10130:     }
                   10131: }
                   10132: 
1.596.2.12.2.  (raeburn 10133:): sub init_old_essays {
                   10134:):     my ($symb,$apath,$adom,$aname) = @_;
                   10135:):     if ($symb ne '') {
                   10136:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10137:):         if (keys(%essays) > 0) {
                   10138:):             $old_essays{$symb} = \%essays;
                   10139:):         }
                   10140:):     }
                   10141:):     return;
                   10142:): }
                   10143:): 
                   10144:): sub reset_old_essays {
                   10145:):     undef(%old_essays);
                   10146:): }
                   10147:): 
1.400     www      10148: sub gather_clicker_ids {
1.408     albertel 10149:     my %clicker_ids;
1.400     www      10150: 
                   10151:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10152: 
                   10153:     # Set up a couple variables.
1.407     albertel 10154:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10155:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10156:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10157: 
1.407     albertel 10158:     foreach my $student (keys(%$classlist)) {
1.438     www      10159:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10160:         my $username = $classlist->{$student}->[$username_idx];
                   10161:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10162:         my $clickers =
1.408     albertel 10163: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10164:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10165:             $id=~s/^[\#0]+//;
1.421     www      10166:             $id=~s/[\-\:]//g;
1.407     albertel 10167:             if (exists($clicker_ids{$id})) {
1.408     albertel 10168: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10169:             } else {
1.408     albertel 10170: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10171:             }
                   10172:         }
                   10173:     }
1.407     albertel 10174:     return %clicker_ids;
1.400     www      10175: }
                   10176: 
1.402     www      10177: sub gather_adv_clicker_ids {
1.408     albertel 10178:     my %clicker_ids;
1.402     www      10179:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10180:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10181:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10182:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10183:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10184:             my ($puname,$pudom)=split(/\:/,$person);
                   10185:             my $clickers =
1.408     albertel 10186: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10187:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10188: 		$id=~s/^[\#0]+//;
1.421     www      10189:                 $id=~s/[\-\:]//g;
1.408     albertel 10190: 		if (exists($clicker_ids{$id})) {
                   10191: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10192: 		} else {
                   10193: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10194: 		}
1.405     www      10195:             }
1.402     www      10196:         }
                   10197:     }
1.407     albertel 10198:     return %clicker_ids;
1.402     www      10199: }
                   10200: 
1.413     www      10201: sub clicker_grading_parameters {
                   10202:     return ('gradingmechanism' => 'scalar',
                   10203:             'upfiletype' => 'scalar',
                   10204:             'specificid' => 'scalar',
                   10205:             'pcorrect' => 'scalar',
                   10206:             'pincorrect' => 'scalar');
                   10207: }
                   10208: 
1.400     www      10209: sub process_clicker {
1.596.2.12.2.  1(raebur 10210:0):     my ($r,$symb)=@_;
1.400     www      10211:     if (!$symb) {return '';}
                   10212:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10213:0):     $result.=&Apache::loncommon::start_data_table().
                   10214:0):              &Apache::loncommon::start_data_table_header_row().
                   10215:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10216:0):              &Apache::loncommon::end_data_table_header_row().
                   10217:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10218: # Attempt to restore parameters from last session, set defaults if not present
                   10219:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10220:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10221:                                                  \%Saveable_Parameters);
                   10222:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10223:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10224:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10225:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10226: 
                   10227:     my %checked;
1.521     www      10228:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10229:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10230:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10231:        }
                   10232:     }
                   10233: 
1.596.2.12.2.  1(raebur 10234:0):     my $upload=&mt("Evaluate File");
1.400     www      10235:     my $type=&mt("Type");
1.402     www      10236:     my $attendance=&mt("Award points just for participation");
                   10237:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10238:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10239:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10240:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10241:     my $pcorrect=&mt("Percentage points for correct solution");
                   10242:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10243:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10244:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10245:):                                                     'interwrite' => 'interwrite PRS',
                   10246:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10247:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10248:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10249: function sanitycheck() {
                   10250: // Accept only integer percentages
                   10251:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10252:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10253: // Find out grading choice
                   10254:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10255:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10256:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10257:       }
                   10258:    }
                   10259: // By default, new choice equals user selection
                   10260:    newgradingchoice=gradingchoice;
                   10261: // Not good to give more points for false answers than correct ones
                   10262:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10263:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10264:    }
                   10265: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10266:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10267:       document.forms.gradesupload.pcorrect.value=100;
                   10268:       document.forms.gradesupload.pincorrect.value=100;
                   10269:    }
                   10270: // If the values are different, cannot be attendance only
                   10271:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10272:        (gradingchoice=='attendance')) {
                   10273:        newgradingchoice='personnel';
                   10274:    }
                   10275: // Change grading choice to new one
                   10276:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10277:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10278:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10279:       } else {
                   10280:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10281:       }
                   10282:    }
                   10283: // Remember the old state
                   10284:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10285: }
1.596.2.12.2.  1(raebur 10286:0): ENDUPFORM
                   10287:0):     $result.= <<ENDUPFORM;
1.400     www      10288: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10289: <input type="hidden" name="symb" value="$symb" />
                   10290: <input type="hidden" name="command" value="processclickerfile" />
                   10291: <input type="file" name="upfile" size="50" />
                   10292: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10293:0): ENDUPFORM
                   10294:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10295:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10296:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10297: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10298: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10299: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10300: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10301: <br />&nbsp;&nbsp;&nbsp;
                   10302: <input type="text" name="givenanswer" size="50" />
1.413     www      10303: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10304:0): ENDGRADINGFORM
                   10305:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10306:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10307:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10308: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10309: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10310: </form>
1.596.2.12.2.  1(raebur 10311:0): ENDPERCFORM
                   10312:0):     $result.='</td>'.
                   10313:0):              &Apache::loncommon::end_data_table_row().
                   10314:0):              &Apache::loncommon::end_data_table();
1.400     www      10315:     return $result;
                   10316: }
                   10317: 
                   10318: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10319:0):     my ($r,$symb) = @_;
1.400     www      10320:     if (!$symb) {return '';}
1.413     www      10321: 
                   10322:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10323:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10324:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10325:0):     my $result='';
1.404     www      10326:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10327: 	$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 10328:0): 	return $result;
1.404     www      10329:     }
1.522     www      10330:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10331:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10332:0):         return $result;
1.521     www      10333:     }
1.522     www      10334:     my $foundgiven=0;
1.521     www      10335:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10336:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10337:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10338:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10339:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10340:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10341:         $foundgiven=$#answers+1;
1.521     www      10342:     }
1.407     albertel 10343:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10344:     my %correct_ids;
1.404     www      10345:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10346: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10347:     }
                   10348:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10349: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10350: 	   $correct_id=~tr/a-z/A-Z/;
                   10351: 	   $correct_id=~s/\s//gs;
                   10352: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10353:            $correct_id=~s/[\-\:]//g;
1.414     www      10354:            if ($correct_id) {
                   10355: 	      $correct_ids{$correct_id}='specified';
                   10356:            }
                   10357:         }
1.400     www      10358:     }
1.404     www      10359:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10360: 	$result.=&mt('Score based on attendance only');
1.521     www      10361:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10362:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10363:     } else {
1.408     albertel 10364: 	my $number=0;
1.411     www      10365: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10366: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10367: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10368: 	    if ($correct_ids{$id} eq 'specified') {
                   10369: 		$result.=&mt('specified');
                   10370: 	    } else {
                   10371: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10372: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10373: 	    }
                   10374: 	    $number++;
                   10375: 	}
1.411     www      10376:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10377:3):         if ($number==0) {
                   10378:3):             $result .=
                   10379:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10380:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10381:0):             return $result;
          5(raebur 10382:3):         }
1.404     www      10383:     }
1.405     www      10384:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10385:3):         $result .=
                   10386:3):             &Apache::lonhtmlcommon::confirm_success(
                   10387:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10388:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10389:0):         return $result;
1.405     www      10390:     }
1.596.2.12.2.  7(raebur 10391:9):     my $mimetype;
                   10392:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10393:9):         my $mm = new File::MMagic;
                   10394:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10395:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10396:9):             $result.= '<p>'.
                   10397:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10398:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10399:0):             return $result;
          7(raebur 10400:9):         }
                   10401:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10402:9):         $result .= '<p>'.
                   10403:9):             &Apache::lonhtmlcommon::confirm_success(
                   10404:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10405:0):         return $result;
          7(raebur 10406:9):     }
1.410     www      10407: 
                   10408: # Were able to get all the info needed, now analyze the file
                   10409: 
1.411     www      10410:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10411:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10412:0):     $result.=&Apache::loncommon::start_data_table().
                   10413:0):              &Apache::loncommon::start_data_table_header_row().
                   10414:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10415:0):              &Apache::loncommon::end_data_table_header_row().
                   10416:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10417:0): <td>
1.410     www      10418: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10419: <input type="hidden" name="symb" value="$symb" />
                   10420: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10421: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10422: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10423: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10424: ENDHEADER
1.522     www      10425:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10426:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10427:     } 
1.408     albertel 10428:     my %responses;
                   10429:     my @questiontitles;
1.405     www      10430:     my $errormsg='';
                   10431:     my $number=0;
                   10432:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10433:9):         if ($mimetype eq 'text/plain') {
                   10434:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10435:9):         } elsif ($mimetype eq 'text/html') {
                   10436:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10437:9):         }
                   10438:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10439:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10440:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10441:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10442:):     }
1.411     www      10443:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10444:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10445:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10446:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10447:              '<br />';
1.522     www      10448:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10449:        $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 10450:0):        return $result;
1.522     www      10451:     } 
1.414     www      10452: # Remember Question Titles
                   10453: # FIXME: Possibly need delimiter other than ":"
                   10454:     for (my $i=0;$i<$number;$i++) {
                   10455:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10456:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10457:     }
1.411     www      10458:     my $correct_count=0;
                   10459:     my $student_count=0;
                   10460:     my $unknown_count=0;
1.414     www      10461: # Match answers with usernames
                   10462: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10463:     foreach my $id (keys(%responses)) {
1.410     www      10464:        if ($correct_ids{$id}) {
1.414     www      10465:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10466:           $correct_count++;
1.410     www      10467:        } elsif ($clicker_ids{$id}) {
1.437     www      10468:           if ($clicker_ids{$id}=~/\,/) {
                   10469: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10470:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10471:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10472:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10473:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10474:                            "<select name='multi".$id."'>";
                   10475:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10476:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10477:              }
                   10478:              $result.='</select>';
                   10479:              $unknown_count++;
                   10480:           } else {
                   10481: # Good: found one and only one user with the right clicker
                   10482:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10483:              $student_count++;
                   10484:           }
1.410     www      10485:        } else {
1.596.2.12.2.  1(raebur 10486:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10487:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10488:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10489:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10490:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10491:                    "\n".&mt("Domain").": ".
                   10492:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10493:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10494:           $unknown_count++;
1.410     www      10495:        }
1.405     www      10496:     }
1.412     www      10497:     $result.='<hr />'.
                   10498:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10499:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10500:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10501:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10502:        } elsif ($correct_count>1) {
1.414     www      10503:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10504:        }
                   10505:     }
1.428     www      10506:     if ($number<1) {
                   10507:        $errormsg.="Found no questions.";
                   10508:     }
1.412     www      10509:     if ($errormsg) {
                   10510:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10511:     } else {
                   10512:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10513:     }
1.596.2.12.2.  1(raebur 10514:0):     $result.='</form></td>'.
                   10515:0):              &Apache::loncommon::end_data_table_row().
                   10516:0):              &Apache::loncommon::end_data_table();
                   10517:0):     return $result;
1.400     www      10518: }
                   10519: 
1.405     www      10520: sub iclicker_eval {
1.406     www      10521:     my ($questiontitles,$responses)=@_;
1.405     www      10522:     my $number=0;
                   10523:     my $errormsg='';
                   10524:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10525:         my %components=&Apache::loncommon::record_sep($line);
                   10526:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10527: 	if ($entries[0] eq 'Question') {
                   10528: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10529: 		$$questiontitles[$number]=$entries[$i];
                   10530: 		$number++;
                   10531: 	    }
                   10532: 	}
                   10533: 	if ($entries[0]=~/^\#/) {
                   10534: 	    my $id=$entries[0];
                   10535: 	    my @idresponses;
                   10536: 	    $id=~s/^[\#0]+//;
                   10537: 	    for (my $i=0;$i<$number;$i++) {
                   10538: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10539:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10540: 		push(@idresponses,$entries[$idx]);
                   10541: 	    }
                   10542: 	    $$responses{$id}=join(',',@idresponses);
                   10543: 	}
1.405     www      10544:     }
                   10545:     return ($errormsg,$number);
                   10546: }
                   10547: 
1.596.2.12.2.  7(raebur 10548:9): sub iclickerxml_eval {
                   10549:9):     my ($questiontitles,$responses)=@_;
                   10550:9):     my $number=0;
                   10551:9):     my $errormsg='';
                   10552:9):     my @state;
                   10553:9):     my %respbyid;
                   10554:9):     my $p = HTML::Parser->new
                   10555:9):     (
                   10556:9):         xml_mode => 1,
                   10557:9):         start_h =>
                   10558:9):             [sub {
                   10559:9):                  my ($tagname,$attr) = @_;
                   10560:9):                  push(@state,$tagname);
                   10561:9):                  if ("@state" eq "ssn p") {
                   10562:9):                      my $title = $attr->{qn};
                   10563:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10564:9):                      $questiontitles->[$number]=$title;
                   10565:9):                  } elsif ("@state" eq "ssn p v") {
                   10566:9):                      my $id = $attr->{id};
                   10567:9):                      my $entry = $attr->{ans};
                   10568:9):                      $id=~s/^[\#0]+//;
                   10569:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10570:9):                      $respbyid{$id}[$number] = $entry;
                   10571:9):                  }
                   10572:9):             }, "tagname, attr"],
                   10573:9):          end_h =>
                   10574:9):                [sub {
                   10575:9):                    my ($tagname) = @_;
                   10576:9):                    if ("@state" eq "ssn p") {
                   10577:9):                        $number++;
                   10578:9):                    }
                   10579:9):                    pop(@state);
                   10580:9):                 }, "tagname"],
                   10581:9):     );
                   10582:9): 
                   10583:9):     $p->parse($env{'form.upfile'});
                   10584:9):     $p->eof;
                   10585:9):     foreach my $id (keys(%respbyid)) {
                   10586:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10587:9):     }
                   10588:9):     return ($errormsg,$number);
                   10589:9): }
                   10590:9): 
1.419     www      10591: sub interwrite_eval {
                   10592:     my ($questiontitles,$responses)=@_;
                   10593:     my $number=0;
                   10594:     my $errormsg='';
1.420     www      10595:     my $skipline=1;
                   10596:     my $questionnumber=0;
                   10597:     my %idresponses=();
1.419     www      10598:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10599:         my %components=&Apache::loncommon::record_sep($line);
                   10600:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10601:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10602:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10603:         next if $skipline;
                   10604:         if ($entries[0]!=$questionnumber) {
                   10605:            $questionnumber=$entries[0];
                   10606:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10607:            $number++;
1.419     www      10608:         }
1.420     www      10609:         my $id=$entries[4];
                   10610:         $id=~s/^[\#0]+//;
1.421     www      10611:         $id=~s/^v\d*\://i;
                   10612:         $id=~s/[\-\:]//g;
1.420     www      10613:         $idresponses{$id}[$number]=$entries[6];
                   10614:     }
1.524     raeburn  10615:     foreach my $id (keys(%idresponses)) {
1.420     www      10616:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10617:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10618:     }
                   10619:     return ($errormsg,$number);
                   10620: }
                   10621: 
1.596.2.12.2.  (raeburn 10622:): sub turning_eval {
                   10623:):     my ($questiontitles,$responses)=@_;
                   10624:):     my $number=0;
                   10625:):     my $errormsg='';
                   10626:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10627:):         my %components=&Apache::loncommon::record_sep($line);
                   10628:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10629:):         if ($#entries>$number) { $number=$#entries; }
                   10630:):         my $id=$entries[0];
                   10631:):         my @idresponses;
                   10632:):         $id=~s/^[\#0]+//;
                   10633:):         unless ($id) { next; }
                   10634:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10635:):             $entries[$idx]=~s/\,/\;/g;
                   10636:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10637:):             push(@idresponses,$entries[$idx]);
                   10638:):         }
                   10639:):         $$responses{$id}=join(',',@idresponses);
                   10640:):     }
                   10641:):     for (my $i=1; $i<=$number; $i++) {
                   10642:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10643:):     }
                   10644:):     return ($errormsg,$number);
                   10645:): }
                   10646:): 
1.414     www      10647: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10648:0):     my ($r,$symb) = @_;
1.414     www      10649:     if (!$symb) {return '';}
1.416     www      10650: # See which part we are saving to
1.582     raeburn  10651:     my $res_error;
                   10652:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10653:     if ($res_error) {
                   10654:         return &navmap_errormsg();
                   10655:     }
1.416     www      10656: # FIXME: This should probably look for the first handgradeable part
                   10657:     my $part=$$partlist[0];
                   10658: # Start screen output
1.596.2.12.2.  1(raebur 10659:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10660:0):                  &Apache::loncommon::start_data_table_header_row().
                   10661:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10662:0):                  &Apache::loncommon::end_data_table_header_row().
                   10663:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10664: # Get correct result
                   10665: # FIXME: Possibly need delimiter other than ":"
                   10666:     my @correct=();
1.415     www      10667:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10668:     my $number=$env{'form.number'};
                   10669:     if ($gradingmechanism ne 'attendance') {
1.414     www      10670:        foreach my $key (keys(%env)) {
                   10671:           if ($key=~/^form\.correct\:/) {
                   10672:              my @input=split(/\,/,$env{$key});
                   10673:              for (my $i=0;$i<=$#input;$i++) {
                   10674:                  if (($correct[$i]) && ($input[$i]) &&
                   10675:                      ($correct[$i] ne $input[$i])) {
                   10676:                     $result.='<br /><span class="LC_warning">'.
                   10677:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10678:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10679:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10680:                     $correct[$i]=$input[$i];
                   10681:                  }
                   10682:              }
                   10683:           }
                   10684:        }
1.415     www      10685:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10686:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10687:              $result.='<br /><span class="LC_error">'.
                   10688:                       &mt('No correct result given for question "[_1]"!',
                   10689:                           $env{'form.question:'.$i}).'</span>';
                   10690:           }
                   10691:        }
1.596.2.4  raeburn  10692:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10693:     }
                   10694: # Start grading
1.415     www      10695:     my $pcorrect=$env{'form.pcorrect'};
                   10696:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10697:     my $storecount=0;
1.596.2.4  raeburn  10698:     my %users=();
1.415     www      10699:     foreach my $key (keys(%env)) {
1.420     www      10700:        my $user='';
1.415     www      10701:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10702:           $user=$1;
                   10703:        }
                   10704:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10705:           my $id=$1;
                   10706:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10707:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10708:           } elsif ($env{'form.multi'.$id}) {
                   10709:              $user=$env{'form.multi'.$id};
1.420     www      10710:           }
                   10711:        }
1.596.2.4  raeburn  10712:        if ($user) {
                   10713:           if ($users{$user}) {
                   10714:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10715:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10716:                       '</span><br />';
                   10717:           }
                   10718:           $users{$user}=1;
1.415     www      10719:           my @answer=split(/\,/,$env{$key});
                   10720:           my $sum=0;
1.522     www      10721:           my $realnumber=$number;
1.415     www      10722:           for (my $i=0;$i<$number;$i++) {
1.576     www      10723:              if  ($correct[$i] eq '-') {
                   10724:                 $realnumber--;
1.596.2.12.2.  1(raebur 10725:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      10726:                 if ($gradingmechanism eq 'attendance') {
                   10727:                    $sum+=$pcorrect;
1.576     www      10728:                 } elsif ($correct[$i] eq '*') {
1.522     www      10729:                    $sum+=$pcorrect;
1.415     www      10730:                 } else {
1.596.2.4  raeburn  10731: # We actually grade if correct or not
                   10732:                    my $increment=$pincorrect;
                   10733: # Special case: numerical answer "0"
                   10734:                    if ($correct[$i] eq '0') {
                   10735:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10736:                          $increment=$pcorrect;
                   10737:                       }
                   10738: # General numerical answer, both evaluate to something non-zero
                   10739:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10740:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10741:                          $increment=$pcorrect;
                   10742:                       }
                   10743: # Must be just alphanumeric
                   10744:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10745:                       $increment=$pcorrect;
1.415     www      10746:                    }
1.596.2.4  raeburn  10747:                    $sum+=$increment;
1.415     www      10748:                 }
                   10749:              }
                   10750:           }
1.522     www      10751:           my $ave=$sum/(100*$realnumber);
1.416     www      10752: # Store
                   10753:           my ($username,$domain)=split(/\:/,$user);
                   10754:           my %grades=();
                   10755:           $grades{"resource.$part.solved"}='correct_by_override';
                   10756:           $grades{"resource.$part.awarded"}=$ave;
                   10757:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10758:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10759:                                                  $env{'request.course.id'},
                   10760:                                                  $domain,$username);
                   10761:           if ($returncode ne 'ok') {
                   10762:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10763:           } else {
                   10764:              $storecount++;
                   10765:           }
1.415     www      10766:        }
                   10767:     }
                   10768: # We are done
1.549     hauer    10769:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10770:              '</td>'.
                   10771:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 10772:0):              &Apache::loncommon::end_data_table();
                   10773:0):     return $result;
1.414     www      10774: }
                   10775: 
1.582     raeburn  10776: sub navmap_errormsg {
                   10777:     return '<div class="LC_error">'.
                   10778:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10779:            &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  10780:            '</div>';
                   10781: }
                   10782: 
1.596.2.12.2.  (raeburn 10783:): sub startpage {
          1(raebur 10784:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
          9(raebur 10785:9):     my %args;
                   10786:9):     if ($onload) {
                   10787:9):          my %loaditems = (
                   10788:9):                         'onload' => $onload,
                   10789:9):                       );
                   10790:9):          $args{'add_entries'} = \%loaditems;
                   10791:9):     }
          (raeburn 10792:):     if ($nomenu) {
          9(raebur 10793:9):         $args{'only_body'} = 1;
                   10794:9):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
          (raeburn 10795:):     } else {
          1(raebur 10796:0):         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
          9(raebur 10797:9):         $args{'bread_crumbs'} = $crumbs;
                   10798:9):         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
          (raeburn 10799:):     }
                   10800:):     unless ($nodisplayflag) {
          1(raebur 10801:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 10802:):     }
                   10803:): }
                   10804:): 
          1(raebur 10805:0): sub select_problem {
                   10806:0):     my ($r)=@_;
                   10807:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   10808:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   10809:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10810:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10811:0): }
                   10812:0): 
1.1       albertel 10813: sub handler {
1.41      ng       10814:     my $request=$_[0];
1.434     albertel 10815:     &reset_caches();
1.596.2.4  raeburn  10816:     if ($request->header_only) {
                   10817:         &Apache::loncommon::content_type($request,'text/html');
                   10818:         $request->send_http_header;
                   10819:         return OK;
1.41      ng       10820:     }
                   10821:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10822: 
1.596.2.12.2.  1(raebur 10823:0): # see what command we need to execute
                   10824:0):  
1.160     albertel 10825:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10826:     my $command=$commands[0];
1.447     foxr     10827: 
1.596.2.12.2.  1(raebur 10828:0):     &init_perm();
                   10829:0):     if (!$env{'request.course.id'}) {
                   10830:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10831:0):                 ($command =~ /^scantronupload/)) {
                   10832:0):             # Not in a course.
                   10833:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10834:0):             return HTTP_NOT_ACCEPTABLE;
                   10835:0):         }
                   10836:0):     } elsif (!%perm) {
                   10837:0):         $request->internal_redirect('/adm/quickgrades');
                   10838:0):         return OK;
                   10839:0):     }
                   10840:0):     &Apache::loncommon::content_type($request,'text/html');
                   10841:0):     $request->send_http_header;
                   10842:0): 
1.160     albertel 10843:     if ($#commands > 0) {
                   10844: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10845:     }
1.447     foxr     10846: 
1.596.2.12.2.  1(raebur 10847:0): # see what the symb is
                   10848:0): 
                   10849:0):     my $symb=$env{'form.symb'};
                   10850:0):     unless ($symb) {
                   10851:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10852:0):        $symb=&Apache::lonnet::symbread($url);
                   10853:0):     }
                   10854:0):     &Apache::lonenc::check_decrypt(\$symb);
                   10855:0): 
1.513     foxr     10856:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 10857:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   10858:0): #
                   10859:0): # Not called from a resource, but inside a course
                   10860:0): #
                   10861:0):         &startpage($request,undef,[],1,1);
                   10862:0):         &select_problem($request);
1.41      ng       10863:     } else {
1.596.2.12.2.  1(raebur 10864:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   10865:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 10866:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10867:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10868:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10869:):                                               $env{'form.userdom'});
                   10870:):             }
          1(raebur 10871:0):             my $divforres;
                   10872:0):             if ($env{'form.student'} eq '') {
                   10873:0):                 $js .= &part_selector_js();
                   10874:0):                 $onload = "toggleParts('gradesub');";
                   10875:0):             } else {
                   10876:0):                 $divforres = 1;
                   10877:0):             }
                   10878:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
          (raeburn 10879:):             if ($versionform) {
          2(raebur 10880:0):                 if ($divforres) {
                   10881:0):                     $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   10882:0):                 }
          (raeburn 10883:):                 $request->print($versionform);
                   10884:):             }
          1(raebur 10885:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 10886:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10887:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10888:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10889:):                                           $env{'form.userdom'},
                   10890:):                                           $env{'form.inhibitmenu'});
                   10891:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10892:):             if ($versionform) {
                   10893:):                 $request->print($versionform);
                   10894:):             }
                   10895:):             $request->print('<br clear="all" />');
                   10896:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 10897:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   10898:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10899:0):                                        {href=>'',text=>'Select student'}],1,1);
                   10900:0):             &pickStudentPage($request,$symb);
                   10901:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
                   10902:0):             &startpage($request,$symb,
                   10903:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10904:0):                                        {href=>'',text=>'Select student'},
                   10905:0):                                        {href=>'',text=>'Grade student'}],1,1);
                   10906:0):             &displayPage($request,$symb);
                   10907:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   10908:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10909:0):                                        {href=>'',text=>'Select student'},
                   10910:0):                                        {href=>'',text=>'Grade student'},
                   10911:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   10912:0):             &updateGradeByPage($request,$symb);
                   10913:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
                   10914:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10915:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
                   10916:0):             &processGroup($request,$symb);
                   10917:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   10918:0):             &startpage($request,$symb);
                   10919:0):             $request->print(&grading_menu($request,$symb));
                   10920:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   10921:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   10922:0):             $request->print(&submit_options($request,$symb));
                   10923:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   10924:0):             my $js = &part_selector_js();
                   10925:0):             my $onload = "toggleParts('gradesub');";
                   10926:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   10927:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   10928:0):             $request->print(&listStudents($request,$symb,'graded'));
                   10929:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   10930:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   10931:0):             $request->print(&submit_options_table($request,$symb));
                   10932:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   10933:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   10934:0):             $request->print(&submit_options_sequence($request,$symb));
                   10935:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   10936:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   10937:0):             $request->print(&viewgrades($request,$symb));
                   10938:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   10939:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10940:0):                                        {href=>'',text=>'Store grades'}]);
                   10941:0):             $request->print(&processHandGrade($request,$symb));
                   10942:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   10943:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10944:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10945:0):                                                                              text=>"Modify grades"},
                   10946:0):                                        {href=>'', text=>"Store grades"}]);
                   10947:0):             $request->print(&editgrades($request,$symb));
                   10948:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   10949:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   10950:0):             $request->print(&initialverifyreceipt($request,$symb));
                   10951:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   10952:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10953:0):                                        {href=>'',text=>'Verification Result'}]);
                   10954:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      10955:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10956:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   10957:0):             $request->print(&process_clicker($request,$symb));
1.400     www      10958:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10959:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10960:0):                                        {href=>'', text=>'Process clicker file'}]);
                   10961:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      10962:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10963:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10964:0):                                        {href=>'', text=>'Process clicker file'},
                   10965:0):                                        {href=>'', text=>'Store grades'}]);
                   10966:0):             $request->print(&assign_clicker_grades($request,$symb));
                   10967:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   10968:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10969:0):             $request->print(&upcsvScores_form($request,$symb));
                   10970:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   10971:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10972:0):             $request->print(&csvupload($request,$symb));
                   10973:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   10974:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10975:0):             $request->print(&csvuploadmap($request,$symb));
                   10976:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   10977:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   10978:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10979:0):                 $request->print(&csvuploadoptions($request,$symb));
                   10980:0):             } else {
                   10981:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10982:0):                     $env{'form.upfile_associate'} = 'reverse';
                   10983:0):                 } else {
                   10984:0):                     $env{'form.upfile_associate'} = 'forward';
                   10985:0):                 }
                   10986:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10987:0):                 $request->print(&csvuploadmap($request,$symb));
                   10988:0):             }
                   10989:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10990:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10991:0):             $request->print(&csvuploadassign($request,$symb));
                   10992:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   10993:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10994:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   10995:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   10996:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10997:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   10998:0):             $request->print(&scantron_do_warning($request,$symb));
                   10999:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   11000:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11001:0):             $request->print(&scantron_validate_file($request,$symb));
                   11002:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   11003:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11004:0):             $request->print(&scantron_process_students($request,$symb));
                   11005:0):         } elsif ($command eq 'scantronupload' &&
                   11006:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11007:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11008:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11009:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   11010:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   11011:0):         } elsif ($command eq 'scantronupload_save' &&
                   11012:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   11013:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11014:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11015:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11016:0):         } elsif ($command eq 'scantron_download' &&
                   11017:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11018:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11019:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11020:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11021:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11022:0):             $request->print(&checkscantron_results($request,$symb));
                   11023:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11024:0):             my $js = &part_selector_js();
                   11025:0):             my $onload = "toggleParts('gradingMenu');";
                   11026:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11027:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11028:0):             $request->print(&submit_options_download($request,$symb));
                   11029:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11030:0):             &startpage($request,$symb,
                   11031:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11032:0):     {href=>'', text=>'Download submitted files'}],
                   11033:0):                undef,undef,undef,undef,undef,undef,undef,1);
          2(raebur 11034:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
          1(raebur 11035:0):             &submit_download_link($request,$symb);
                   11036:0):         } elsif ($command) {
                   11037:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11038:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11039:0):         }
1.2       albertel 11040:     }
1.513     foxr     11041:     if ($ssi_error) {
                   11042: 	&ssi_print_error($request);
                   11043:     }
1.353     albertel 11044:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11045:     &reset_caches();
1.596.2.4  raeburn  11046:     return OK;
1.44      ng       11047: }
                   11048: 
1.1       albertel 11049: 1;
                   11050: 
1.13      albertel 11051: __END__;
1.531     jms      11052: 
                   11053: 
                   11054: =head1 NAME
                   11055: 
                   11056: Apache::grades
                   11057: 
                   11058: =head1 SYNOPSIS
                   11059: 
                   11060: Handles the viewing of grades.
                   11061: 
                   11062: This is part of the LearningOnline Network with CAPA project
                   11063: described at http://www.lon-capa.org.
                   11064: 
                   11065: =head1 OVERVIEW
                   11066: 
                   11067: Do an ssi with retries:
                   11068: While I'd love to factor out this with the vesrion in lonprintout,
                   11069: 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
                   11070: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11071: 
                   11072: At least the logic that drives this has been pulled out into loncommon.
                   11073: 
                   11074: 
                   11075: 
                   11076: ssi_with_retries - Does the server side include of a resource.
                   11077:                      if the ssi call returns an error we'll retry it up to
                   11078:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11079:4):                      If we still have a problem, no text is appended to the
1.531     jms      11080:                      output and we set some global variables.
                   11081:                      to indicate to the caller an SSI error occurred.  
                   11082:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11083:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11084:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11085:                      by informing the user that this happened.
                   11086: 
                   11087: Parameters:
                   11088:   resource   - The resource to include.  This is passed directly, without
                   11089:                interpretation to lonnet::ssi.
                   11090:   form       - The form hash parameters that guide the interpretation of the resource
                   11091:                
                   11092:   retries    - Number of retries allowed before giving up completely.
                   11093: Returns:
                   11094:   On success, returns the rendered resource identified by the resource parameter.
                   11095: Side Effects:
                   11096:   The following global variables can be set:
                   11097:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11098:                               It is up to the caller to initialize this to false
                   11099:                               if desired.
                   11100:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11101:                               of the resource that could not be rendered by the ssi
                   11102:                               call.
                   11103:    ssi_error_message   - The error string fetched from the ssi response
                   11104:                               in the event of an error.
                   11105: 
                   11106: 
                   11107: =head1 HANDLER SUBROUTINE
                   11108: 
                   11109: ssi_with_retries()
                   11110: 
                   11111: =head1 SUBROUTINES
                   11112: 
                   11113: =over
                   11114: 
                   11115: =item scantron_get_correction() : 
                   11116: 
                   11117:    Builds the interface screen to interact with the operator to fix a
                   11118:    specific error condition in a specific scanline
                   11119: 
                   11120:  Arguments:
                   11121:     $r           - Apache request object
                   11122:     $i           - number of the current scanline
                   11123:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11124:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11125:     $line        - full contents of the current scanline
                   11126:     $error       - error condition, valid values are
                   11127:                    'incorrectCODE', 'duplicateCODE',
                   11128:                    'doublebubble', 'missingbubble',
                   11129:                    'duplicateID', 'incorrectID'
                   11130:     $arg         - extra information needed
                   11131:        For errors:
                   11132:          - duplicateID   - paper number that this studentID was seen before on
                   11133:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11134:                            seen on before
                   11135:          - incorrectCODE - current incorrect CODE 
                   11136:          - doublebubble  - array ref of the bubble lines that have double
                   11137:                            bubble errors
                   11138:          - missingbubble - array ref of the bubble lines that have missing
                   11139:                            bubble errors
                   11140: 
1.596.2.12.2.  6(raebur 11141:3):    $randomorder - True if exam folder has randomorder set
                   11142:3):    $randompick  - True if exam folder has randompick set
                   11143:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11144:3):                      for current line to question number used for same question
                   11145:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11146:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11147:3):                   and value is number of first bubble line for current student
                   11148:3):                   or code-based randompick and/or randomorder.
                   11149:3): 
                   11150:3): 
1.531     jms      11151: =item  scantron_get_maxbubble() : 
                   11152: 
1.582     raeburn  11153:    Arguments:
                   11154:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11155:                       failure to retrieve a navmap object.
                   11156:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11157:        calling routine should trap the error condition and display the warning
                   11158:        found in &navmap_errormsg().
                   11159: 
1.596.2.12.2.  (raeburn 11160:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11161:): 
1.531     jms      11162:    Returns the maximum number of bubble lines that are expected to
                   11163:    occur. Does this by walking the selected sequence rendering the
                   11164:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11165:    for what the current value of the problem counter is.
                   11166: 
                   11167:    Caches the results to $env{'form.scantron_maxbubble'},
                   11168:    $env{'form.scantron.bubble_lines.n'}, 
                   11169:    $env{'form.scantron.first_bubble_line.n'} and
                   11170:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11171:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11172:    lines for response n and number of the first bubble line for response n,
                   11173:    and a comma separated list of numbers of bubble lines for sub-questions
                   11174:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11175: 
                   11176: 
                   11177: =item  scantron_validate_missingbubbles() : 
                   11178: 
                   11179:    Validates all scanlines in the selected file to not have any
                   11180:     answers that don't have bubbles that have not been verified
                   11181:     to be bubble free.
                   11182: 
                   11183: =item  scantron_process_students() : 
                   11184: 
1.596.2.6  raeburn  11185:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11186: 
                   11187:    The parsed scanline hash is added to %env 
                   11188: 
                   11189:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11190:    foreach resource , with the form data of
                   11191: 
                   11192: 	'submitted'     =>'scantron' 
                   11193: 	'grade_target'  =>'grade',
                   11194: 	'grade_username'=> username of student
                   11195: 	'grade_domain'  => domain of student
                   11196: 	'grade_courseid'=> of course
                   11197: 	'grade_symb'    => symb of resource to grade
                   11198: 
                   11199:     This triggers a grading pass. The problem grading code takes care
                   11200:     of converting the bubbled letter information (now in %env) into a
                   11201:     valid submission.
                   11202: 
                   11203: =item  scantron_upload_scantron_data() :
                   11204: 
1.596.2.6  raeburn  11205:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11206: 
                   11207: =item  scantron_upload_scantron_data_save() : 
                   11208: 
                   11209:    Adds a provided bubble information data file to the course if user
                   11210:    has the correct privileges to do so. 
                   11211: 
                   11212: =item  valid_file() :
                   11213: 
                   11214:    Validates that the requested bubble data file exists in the course.
                   11215: 
                   11216: =item  scantron_download_scantron_data() : 
                   11217: 
                   11218:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11219:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11220:    course.
                   11221: 
                   11222: =item  scantron_validate_ID() : 
                   11223: 
                   11224:    Validates all scanlines in the selected file to not have any
1.556     weissno  11225:    invalid or underspecified student/employee IDs
1.531     jms      11226: 
1.582     raeburn  11227: =item navmap_errormsg() :
                   11228: 
                   11229:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11230:    Should be called whenever the request to instantiate a navmap object fails.  
                   11231: 
1.531     jms      11232: =back
                   11233: 
                   11234: =cut

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