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

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.  1(raebur    4:0): # $Id: grades.pm,v 1.596.2.12.2.50 2020/02/12 17:33:53 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>';
                    292:0):     return $result;
                    293:0): }
                    294:0): 
                    295:0): sub part_selector_js {
                    296:0):     my $js = <<"END";
                    297:0): function toggleParts(formname) {
                    298:0):     if (document.getElementById('LC_partselector')) {
                    299:0):         var index = '';
                    300:0):         if (document.forms.length) {
                    301:0):             for (var i=0; i<document.forms.length; i++) {
                    302:0):                 if (document.forms[i].name == formname) {
                    303:0):                     index = i;
                    304:0):                     break;
                    305:0):                 }
                    306:0):             }
                    307:0):         }
                    308:0):         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
                    309:0):             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
                    310:0):                 if (document.forms[index].elements['chooseparts'][i].checked) {
                    311:0):                    var val = document.forms[index].elements['chooseparts'][i].value;
                    312:0):                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
                    313:0):                         document.getElementById('LC_partselector').style.display = 'block';
                    314:0):                     } else {
                    315:0):                         document.getElementById('LC_partselector').style.display = 'none';
                    316:0):                     }
                    317:0):                 }
                    318:0):             }
                    319:0):         }
                    320:0):     }
                    321:0): }
                    322:0): END
                    323:0):     return &Apache::lonhtmlcommon::scripttag($js);
1.118     ng        324: }
                    325: 
1.434     albertel  326: sub reset_caches {
                    327:     &reset_analyze_cache();
                    328:     &reset_perm();
1.596.2.12.2.  (raeburn  329:):     &reset_old_essays();
1.434     albertel  330: }
                    331: 
                    332: {
                    333:     my %analyze_cache;
1.557     raeburn   334:     my %analyze_cache_formkeys;
1.148     albertel  335: 
1.434     albertel  336:     sub reset_analyze_cache {
                    337: 	undef(%analyze_cache);
1.557     raeburn   338:         undef(%analyze_cache_formkeys);
1.434     albertel  339:     }
                    340: 
                    341:     sub get_analyze {
1.596.2.12.2.  (raeburn  342:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  343: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   344:         if ($type eq 'randomizetry') {
                    345:             if ($trial ne '') {
                    346:                 $key .= "\0".$trial;
                    347:             }
                    348:         }
1.557     raeburn   349: 	if (exists($analyze_cache{$key})) {
                    350:             my $getupdate = 0;
                    351:             if (ref($add_to_hash) eq 'HASH') {
                    352:                 foreach my $item (keys(%{$add_to_hash})) {
                    353:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    354:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    355:                             $getupdate = 1;
                    356:                             last;
                    357:                         }
                    358:                     } else {
                    359:                         $getupdate = 1;
                    360:                     }
                    361:                 }
                    362:             }
                    363:             if (!$getupdate) {
                    364:                 return $analyze_cache{$key};
                    365:             }
                    366:         }
1.434     albertel  367: 
                    368: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    369: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   370:         my %form = ('grade_target'      => 'analyze',
                    371:                     'grade_domain'      => $udom,
                    372:                     'grade_symb'        => $symb,
                    373:                     'grade_courseid'    =>  $env{'request.course.id'},
                    374:                     'grade_username'    => $uname,
                    375:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  376:):         if ($bubbles_per_row ne '') {
                    377:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    378:):         }
1.596.2.2  raeburn   379:         if ($type eq 'randomizetry') {
                    380:             $form{'grade_questiontype'} = $type;
                    381:             if ($rndseed ne '') {
                    382:                 $form{'grade_rndseed'} = $rndseed;
                    383:             }
                    384:         }
1.557     raeburn   385:         if (ref($add_to_hash)) {
                    386:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   387:         }
1.557     raeburn   388: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  389: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    390: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   391:         if (ref($add_to_hash) eq 'HASH') {
                    392:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    393:         } else {
                    394:             $analyze_cache_formkeys{$key} = {};
                    395:         }
1.434     albertel  396: 	return $analyze_cache{$key} = \%analyze;
                    397:     }
                    398: 
                    399:     sub get_order {
1.596.2.2  raeburn   400: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    401: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  402: 	return $analyze->{"$partid.$respid.shown"};
                    403:     }
                    404: 
                    405:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   406: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    407: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    408:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   409:         if (ref($foils) eq 'ARRAY') {
                    410: 	    foreach my $foil (@{$foils}) {
                    411: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    412: 		    return $foil;
                    413: 	        }
1.434     albertel  414: 	    }
                    415: 	}
                    416:     }
1.554     raeburn   417: 
                    418:     sub scantron_partids_tograde {
1.596.2.12.2.  1(raebur  419:7):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   420:         my (%analysis,@parts);
                    421:         if (ref($resource)) {
                    422:             my $symb = $resource->symb();
1.557     raeburn   423:             my $add_to_form;
                    424:             if ($check_for_randomlist) {
                    425:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    426:             }
1.596.2.12.2.  1(raebur  427:7):             if ($scancode) {
                    428:7):                 if (ref($add_to_form) eq 'HASH') {
                    429:7):                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    430:7):                 } else {
                    431:7):                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    432:7):                 }
                    433:7):             }
          (raeburn  434:):             my $analyze =
                    435:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    436:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   437:             if (ref($analyze) eq 'HASH') {
                    438:                 %analysis = %{$analyze};
                    439:             }
                    440:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    441:                 foreach my $part (@{$analysis{'parts'}}) {
                    442:                     my ($id,$respid) = split(/\./,$part);
                    443:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    444:                         push(@parts,$part);
                    445:                     }
                    446:                 }
                    447:             }
                    448:         }
                    449:         return (\%analysis,\@parts);
                    450:     }
                    451: 
1.148     albertel  452: }
1.434     albertel  453: 
1.118     ng        454: #--- Clean response type for display
1.335     albertel  455: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    456: #        response types only.
1.118     ng        457: sub cleanRecord {
1.336     albertel  458:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   459: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  460:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  461:     if ($response =~ /^(option|rank)$/) {
                    462: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  463:4):         my @answer = %answer;
                    464:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  465: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    466: 	my ($toprow,$bottomrow);
                    467: 	foreach my $foil (@$order) {
                    468: 	    if ($grading{$foil} == 1) {
                    469: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    470: 	    } else {
                    471: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    472: 	    }
1.398     albertel  473: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  474: 	}
                    475: 	return '<blockquote><table border="1">'.
1.466     albertel  476: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    477: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   478: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  479:     } elsif ($response eq 'match') {
                    480: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  481:4):         my @answer = %answer;
                    482:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  483: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    484: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    485: 	my ($toprow,$middlerow,$bottomrow);
                    486: 	foreach my $foil (@$order) {
                    487: 	    my $item=shift(@items);
                    488: 	    if ($grading{$foil} == 1) {
                    489: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  490: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  491: 	    } else {
                    492: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  493: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  494: 	    }
1.398     albertel  495: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        496: 	}
1.126     ng        497: 	return '<blockquote><table border="1">'.
1.466     albertel  498: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    499: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  500: 	    $middlerow.'</tr>'.
1.466     albertel  501: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   502: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  503:     } elsif ($response eq 'radiobutton') {
                    504: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  1(raebur  505:0):         my @answer = %answer;
                    506:0):         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  507: 	my ($toprow,$bottomrow);
1.434     albertel  508: 	my $correct = 
1.596.2.2  raeburn   509: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  510: 	foreach my $foil (@$order) {
1.148     albertel  511: 	    if (exists($answer{$foil})) {
1.434     albertel  512: 		if ($foil eq $correct) {
1.466     albertel  513: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  514: 		} else {
1.466     albertel  515: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  516: 		}
                    517: 	    } else {
1.466     albertel  518: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  519: 	    }
1.398     albertel  520: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  521: 	}
                    522: 	return '<blockquote><table border="1">'.
1.466     albertel  523: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    524: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   525: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  526:     } elsif ($response eq 'essay') {
1.257     albertel  527: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        528: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  529: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    530: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        531: 
1.257     albertel  532: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    533: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    534: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    535: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    536: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    537: 	    $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        538: 	}
1.596.2.12.2.  4(raebur  539:8):         $answer = &Apache::lontexconvert::msgtexconverted($answer);
          2(raebur  540:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  541:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  542:4):         my $result=&mt('Smile representation: [_1]',
                    543:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  544: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    545: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    546: 	return $result;
1.335     albertel  547:     } elsif ( $response eq 'Task') {
                    548: 	if ( $answer eq 'SUBMITTED') {
                    549: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  550: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  551: 	    return $result;
                    552: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    553: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    554: 			       keys(%{$record}));
                    555: 	    return join('<br />',($version,@matches));
                    556: 			       
                    557: 			       
                    558: 	} else {
                    559: 	    my $result =
                    560: 		'<p>'
                    561: 		.&mt('Overall result: [_1]',
                    562: 		     $record->{$version."resource.$respid.$partid.status"})
                    563: 		.'</p>';
                    564: 	    
                    565: 	    $result .= '<ul>';
                    566: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    567: 			     keys(%{$record}));
                    568: 	    foreach my $grade (sort(@grade)) {
                    569: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    570: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    571: 				     $dim, $record->{$grade}).
                    572: 			  '</li>';
                    573: 	    }
                    574: 	    $result.='</ul>';
                    575: 	    return $result;
                    576: 	}
1.596.2.12.2.  8(raebur  577:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    578:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  579: 	$answer = 
                    580: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    581: 							      $answer);
1.596.2.12.2.  1(raebur  582:0): 	return $answer;
1.122     ng        583:     }
1.596.2.12.2.  8(raebur  584:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        585: }
                    586: 
                    587: #-- A couple of common js functions
                    588: sub commonJSfunctions {
                    589:     my $request = shift;
1.596.2.12.2.  1(raebur  590:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        591:     function radioSelection(radioButton) {
                    592: 	var selection=null;
                    593: 	if (radioButton.length > 1) {
                    594: 	    for (var i=0; i<radioButton.length; i++) {
                    595: 		if (radioButton[i].checked) {
                    596: 		    return radioButton[i].value;
                    597: 		}
                    598: 	    }
                    599: 	} else {
                    600: 	    if (radioButton.checked) return radioButton.value;
                    601: 	}
                    602: 	return selection;
                    603:     }
                    604: 
                    605:     function pullDownSelection(selectOne) {
                    606: 	var selection="";
                    607: 	if (selectOne.length > 1) {
                    608: 	    for (var i=0; i<selectOne.length; i++) {
                    609: 		if (selectOne[i].selected) {
                    610: 		    return selectOne[i].value;
                    611: 		}
                    612: 	    }
                    613: 	} else {
1.138     albertel  614:             // only one value it must be the selected one
                    615: 	    return selectOne.value;
1.118     ng        616: 	}
                    617:     }
                    618: COMMONJSFUNCTIONS
                    619: }
                    620: 
1.44      ng        621: #--- Dumps the class list with usernames,list of sections,
                    622: #--- section, ids and fullnames for each user.
                    623: sub getclasslist {
1.596.2.12.2.  1(raebur  624:0):     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  625:     my @getsec;
1.450     banghart  626:     my @getgroup;
1.442     banghart  627:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  628:     if (!ref($getsec)) {
                    629: 	if ($getsec ne '' && $getsec ne 'all') {
                    630: 	    @getsec=($getsec);
                    631: 	}
                    632:     } else {
                    633: 	@getsec=@{$getsec};
                    634:     }
                    635:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  636:     if (!ref($getgroup)) {
                    637: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    638: 	    @getgroup=($getgroup);
                    639: 	}
                    640:     } else {
                    641: 	@getgroup=@{$getgroup};
                    642:     }
                    643:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  644: 
1.449     banghart  645:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  646:     # Bail out if we were unable to get the classlist
1.56      matthew   647:     return if (! defined($classlist));
1.449     banghart  648:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   649:     #
                    650:     my %sections;
                    651:     my %fullnames;
1.596.2.12.2.  1(raebur  652:0):     my ($cdom,$cnum,$partlist);
                    653:0):     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    654:0):         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    655:0):         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    656:0):         my $res_error;
                    657:0):         ($partlist) = &response_type($symb,\$res_error);
                    658:0):     }
1.205     matthew   659:     foreach my $student (keys(%$classlist)) {
                    660:         my $end      = 
                    661:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    662:         my $start    = 
                    663:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    664:         my $id       = 
                    665:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    666:         my $section  = 
                    667:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    668:         my $fullname = 
                    669:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    670:         my $status   = 
                    671:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  672:         my $group   = 
                    673:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        674: 	# filter students according to status selected
1.596.2.12.2.  1(raebur  675:0): 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  676: 	    if (!($stu_status =~ $status)) {
1.450     banghart  677: 		delete($classlist->{$student});
1.76      ng        678: 		next;
                    679: 	    }
                    680: 	}
1.450     banghart  681: 	# filter students according to groups selected
1.453     banghart  682: 	my @stu_groups = split(/,/,$group);
1.450     banghart  683: 	if (@getgroup) {
                    684: 	    my $exclude = 1;
1.454     banghart  685: 	    foreach my $grp (@getgroup) {
                    686: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  687: 	            if ($stu_group eq $grp) {
                    688: 	                $exclude = 0;
                    689:     	            } 
1.450     banghart  690: 	        }
1.453     banghart  691:     	        if (($grp eq 'none') && !$group) {
1.596.2.12.2.  1(raebur  692:0):         	    $exclude = 0;
1.453     banghart  693:         	}
1.450     banghart  694: 	    }
                    695: 	    if ($exclude) {
                    696: 	        delete($classlist->{$student});
1.596.2.12.2.  1(raebur  697:0): 		next;
1.450     banghart  698: 	    }
                    699: 	}
1.596.2.12.2.  1(raebur  700:0):         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    701:0):             my $udom =
                    702:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    703:0):             my $uname =
                    704:0):                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    705:0):             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    706:0):                 if ($submitonly eq 'queued') {
                    707:0):                     my %queue_status =
                    708:0):                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    709:0):                                                                 $udom,$uname);
                    710:0):                     if (!defined($queue_status{'gradingqueue'})) {
                    711:0):                         delete($classlist->{$student});
                    712:0):                         next;
                    713:0):                     }
                    714:0):                 } else {
                    715:0):                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    716:0):                     my $submitted = 0;
                    717:0):                     my $graded = 0;
                    718:0):                     my $incorrect = 0;
                    719:0):                     foreach (keys(%status)) {
                    720:0):                         $submitted = 1 if ($status{$_} ne 'nothing');
                    721:0):                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    722:0):                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    723:0): 
                    724:0):                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    725:0):                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    726:0):                             $submitted = 0;
                    727:0):                         }
                    728:0):                     }
                    729:0):                     if (!$submitted && ($submitonly eq 'yes' ||
                    730:0):                                         $submitonly eq 'incorrect' ||
                    731:0):                                         $submitonly eq 'graded')) {
                    732:0):                         delete($classlist->{$student});
                    733:0):                         next;
                    734:0):                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    735:0):                         delete($classlist->{$student});
                    736:0):                         next;
                    737:0):                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    738:0):                         delete($classlist->{$student});
                    739:0):                         next;
                    740:0):                     }
                    741:0):                 }
                    742:0):             }
                    743:0):         }
1.205     matthew   744: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  745: 	if (&canview($section)) {
1.291     albertel  746: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  747: 		$sections{$section}++;
1.450     banghart  748: 		if ($classlist->{$student}) {
                    749: 		    $fullnames{$student}=$fullname;
                    750: 		}
1.103     albertel  751: 	    } else {
1.205     matthew   752: 		delete($classlist->{$student});
1.103     albertel  753: 	    }
                    754: 	} else {
1.205     matthew   755: 	    delete($classlist->{$student});
1.103     albertel  756: 	}
1.44      ng        757:     }
1.56      matthew   758:     my @sections = sort(keys(%sections));
                    759:     return ($classlist,\@sections,\%fullnames);
1.44      ng        760: }
                    761: 
1.103     albertel  762: sub canmodify {
                    763:     my ($sec)=@_;
                    764:     if ($perm{'mgr'}) {
                    765: 	if (!defined($perm{'mgr_section'})) {
                    766: 	    # can modify whole class
                    767: 	    return 1;
                    768: 	} else {
                    769: 	    if ($sec eq $perm{'mgr_section'}) {
                    770: 		#can modify the requested section
                    771: 		return 1;
                    772: 	    } else {
1.596.2.12.2.  1(raebur  773:0): 		# can't modify the requested section
1.103     albertel  774: 		return 0;
                    775: 	    }
                    776: 	}
                    777:     }
                    778:     #can't modify
                    779:     return 0;
                    780: }
                    781: 
                    782: sub canview {
                    783:     my ($sec)=@_;
                    784:     if ($perm{'vgr'}) {
                    785: 	if (!defined($perm{'vgr_section'})) {
1.596.2.12.2.  1(raebur  786:0): 	    # can view whole class
1.103     albertel  787: 	    return 1;
                    788: 	} else {
                    789: 	    if ($sec eq $perm{'vgr_section'}) {
1.596.2.12.2.  1(raebur  790:0): 		#can view the requested section
1.103     albertel  791: 		return 1;
                    792: 	    } else {
1.596.2.12.2.  1(raebur  793:0): 		# can't view the requested section
1.103     albertel  794: 		return 0;
                    795: 	    }
                    796: 	}
                    797:     }
1.596.2.12.2.  1(raebur  798:0):     #can't view
1.103     albertel  799:     return 0;
                    800: }
                    801: 
1.44      ng        802: #--- Retrieve the grade status of a student for all the parts
                    803: sub student_gradeStatus {
1.324     albertel  804:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  805:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        806:     my %partstatus = ();
                    807:     foreach (@$partlist) {
1.128     ng        808: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        809: 	$status              = 'nothing' if ($status eq '');
                    810: 	$partstatus{$_}      = $status;
                    811: 	my $subkey           = "resource.$_.submitted_by";
                    812: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    813:     }
                    814:     return %partstatus;
                    815: }
                    816: 
1.45      ng        817: # hidden form and javascript that calls the form
                    818: # Use by verifyscript and viewgrades
                    819: # Shows a student's view of problem and submission
                    820: sub jscriptNform {
1.324     albertel  821:     my ($symb) = @_;
1.442     banghart  822:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  1(raebur  823:0):     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        824: 	'    function viewOneStudent(user,domain) {'."\n".
                    825: 	'	document.onestudent.student.value = user;'."\n".
                    826: 	'	document.onestudent.userdom.value = domain;'."\n".
                    827: 	'	document.onestudent.submit();'."\n".
                    828: 	'    }'."\n".
1.596.2.12.2.  1(raebur  829:0): 	"\n");
1.45      ng        830:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  831: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  832: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        833: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    834: 	'<input type="hidden" name="student" value="" />'."\n".
                    835: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    836: 	'</form>'."\n";
                    837:     return $jscript;
                    838: }
1.39      ng        839: 
1.447     foxr      840: 
                    841: 
1.315     bowersj2  842: # Given the score (as a number [0-1] and the weight) what is the final
                    843: # point value? This function will round to the nearest tenth, third,
                    844: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  845: sub compute_points {
1.315     bowersj2  846:     my ($score, $weight) = @_;
                    847:     
                    848:     my $tolerance = .00001;
                    849:     my $points = $score * $weight;
                    850: 
                    851:     # Check for nearness to 1/x.
                    852:     my $check_for_nearness = sub {
                    853:         my ($factor) = @_;
                    854:         my $num = ($points * $factor) + $tolerance;
                    855:         my $floored_num = floor($num);
1.316     albertel  856:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  857:             return $floored_num / $factor;
                    858:         }
                    859:         return $points;
                    860:     };
                    861: 
                    862:     $points = $check_for_nearness->(10);
                    863:     $points = $check_for_nearness->(3);
                    864:     $points = $check_for_nearness->(4);
                    865:     
                    866:     return $points;
                    867: }
                    868: 
1.44      ng        869: #------------------ End of general use routines --------------------
1.87      www       870: 
                    871: #
                    872: # Find most similar essay
                    873: #
                    874: 
                    875: sub most_similar {
1.596.2.12.2.  (raeburn  876:):     my ($uname,$udom,$symb,$uessay)=@_;
                    877:): 
                    878:):     unless ($symb) { return ''; }
                    879:): 
                    880:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       881: 
                    882: # ignore spaces and punctuation
                    883: 
                    884:     $uessay=~s/\W+/ /gs;
                    885: 
1.282     www       886: # ignore empty submissions (occuring when only files are sent)
                    887: 
1.596.2.4  raeburn   888:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       889: 
1.87      www       890: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       891:     my $limit=0.6;
1.87      www       892:     my $sname='';
                    893:     my $sdom='';
                    894:     my $scrsid='';
                    895:     my $sessay='';
                    896: # go through all essays ...
1.596.2.12.2.  (raeburn  897:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  898: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       899: # ... except the same student
1.426     albertel  900:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  901:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  902: 	$tessay=~s/\W+/ /gs;
1.87      www       903: # String similarity gives up if not even limit
1.426     albertel  904: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       905: # Found one
1.426     albertel  906: 	if ($tsimilar>$limit) {
                    907: 	    $limit=$tsimilar;
                    908: 	    $sname=$tname;
                    909: 	    $sdom=$tdom;
                    910: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  911:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  912: 	}
1.87      www       913:     }
1.88      www       914:     if ($limit>0.6) {
1.87      www       915:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    916:     } else {
                    917:        return ('','','','',0);
                    918:     }
                    919: }
                    920: 
1.44      ng        921: #-------------------------------------------------------------------
                    922: 
                    923: #------------------------------------ Receipt Verification Routines
1.45      ng        924: #
1.596.2.12.2.  1(raebur  925:0): 
                    926:0): sub initialverifyreceipt {
                    927:0):    my ($request,$symb) = @_;
                    928:0):    &commonJSfunctions($request);
                    929:0):    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
                    930:0):         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    931:0):         '-<input type="text" name="receipt" size="4" />'.
                    932:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    933:0):         '<input type="hidden" name="command" value="verify" />'.
                    934:0):         "</form>\n";
                    935:0): }
                    936:0): 
1.44      ng        937: #--- Check whether a receipt number is valid.---
                    938: sub verifyreceipt {
1.596.2.12.2.  1(raebur  939:0):     my ($request,$symb) = @_;
1.44      ng        940: 
1.257     albertel  941:     my $courseid = $env{'request.course.id'};
1.184     www       942:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  943: 	$env{'form.receipt'};
1.44      ng        944:     $receipt     =~ s/[^\-\d]//g;
                    945: 
1.596.2.12.2.  1(raebur  946:0):     my $title =
1.487     albertel  947: 	'<h3><span class="LC_info">'.
1.596.2.12.2.  1(raebur  948:0): 	&mt('Verifying Receipt Number [_1]',$receipt).
                    949:0): 	'</span></h3>'."\n";
1.44      ng        950: 
                    951:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   952:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  953:     
                    954:     my $receiptparts=0;
1.390     albertel  955:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    956: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  957:     my $parts=['0'];
1.582     raeburn   958:     if ($receiptparts) {
                    959:         my $res_error; 
                    960:         ($parts)=&response_type($symb,\$res_error);
                    961:         if ($res_error) {
                    962:             return &navmap_errormsg();
                    963:         } 
                    964:     }
1.486     albertel  965:     
                    966:     my $header = 
                    967: 	&Apache::loncommon::start_data_table().
                    968: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  969: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    970: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    971: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  972:     if ($receiptparts) {
1.487     albertel  973: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  974:     }
                    975:     $header.=
                    976: 	&Apache::loncommon::end_data_table_header_row();
                    977: 
1.294     albertel  978:     foreach (sort 
                    979: 	     {
                    980: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    981: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    982: 		 }
                    983: 		 return $a cmp $b;
                    984: 	     } (keys(%$fullname))) {
1.44      ng        985: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  986: 	foreach my $part (@$parts) {
                    987: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  988: 		$contents.=
                    989: 		    &Apache::loncommon::start_data_table_row().
                    990: 		    '<td>&nbsp;'."\n".
1.177     albertel  991: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  992: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  993: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    994: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    995: 		if ($receiptparts) {
                    996: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    997: 		}
1.486     albertel  998: 		$contents.= 
                    999: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1000: 		
                   1001: 		$matches++;
                   1002: 	    }
1.44      ng       1003: 	}
                   1004:     }
                   1005:     if ($matches == 0) {
1.584     bisitz   1006:         $string = $title
                   1007:                  .'<p class="LC_warning">'
                   1008:                  .&mt('No match found for the above receipt number.')
                   1009:                  .'</p>';
1.44      ng       1010:     } else {
1.324     albertel 1011: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1012: 	    '<p>'.
1.584     bisitz   1013: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1014: 	    '</p>'.
1.486     albertel 1015: 	    $header.
                   1016: 	    $contents.
                   1017: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1018:     }
1.596.2.12.2.  1(raebur 1019:0):     return $string;
1.44      ng       1020: }
                   1021: 
                   1022: #--- This is called by a number of programs.
                   1023: #--- Called from the Grading Menu - View/Grade an individual student
                   1024: #--- Also called directly when one clicks on the subm button 
                   1025: #    on the problem page.
1.30      ng       1026: sub listStudents {
1.596.2.12.2.  1(raebur 1027:0):     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1028: 
1.257     albertel 1029:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1030:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1031:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1032:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.596.2.12.2.  1(raebur 1033:0):     unless ($submitonly) {
                   1034:0):         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   1035:0):     }
                   1036:0): 
                   1037:0):     my $result='';
                   1038:0):     my $res_error;
                   1039:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
1.118     ng       1040: 
1.596.2.12.2.  1(raebur 1041:0):     my $table;
                   1042:0):     if (ref($partlist) eq 'ARRAY') {
                   1043:0):         if (scalar(@$partlist) > 1 ) {
                   1044:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
                   1045:0):         } elsif ($divforres) {
                   1046:0):             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
                   1047:0):         } else {
                   1048:0):             $table = '<br clear="all" />';
                   1049:0):         }
                   1050:0):     }
1.49      albertel 1051: 
1.596.2.12.2.  6(raebur 1052:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1053: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1054: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1055: 	     );
1.596.2.12.2.  6(raebur 1056:6):     &js_escape(\%js_lt);
          1(raebur 1057:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1058:     function checkSelect(checkBox) {
                   1059: 	var ctr=0;
                   1060: 	var sense="";
                   1061: 	if (checkBox.length > 1) {
                   1062: 	    for (var i=0; i<checkBox.length; i++) {
                   1063: 		if (checkBox[i].checked) {
                   1064: 		    ctr++;
                   1065: 		}
                   1066: 	    }
1.596.2.12.2.  6(raebur 1067:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng       1068: 	} else {
                   1069: 	    if (checkBox.checked) {
                   1070: 		ctr = 1;
                   1071: 	    }
1.596.2.12.2.  6(raebur 1072:6): 	    sense = '$js_lt{'single'}';
1.110     ng       1073: 	}
                   1074: 	if (ctr == 0) {
1.485     albertel 1075: 	    alert(sense);
1.110     ng       1076: 	    return false;
                   1077: 	}
                   1078: 	document.gradesub.submit();
                   1079:     }
                   1080: 
                   1081:     function reLoadList(formname) {
1.112     ng       1082: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1083: 	formname.command.value = 'submission';
                   1084: 	formname.submit();
                   1085:     }
1.45      ng       1086: LISTJAVASCRIPT
                   1087: 
1.118     ng       1088:     &commonJSfunctions($request);
1.41      ng       1089:     $request->print($result);
1.39      ng       1090: 
1.154     albertel 1091:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel 1092: 	"\n".$table;
1.596.2.12.2.  1(raebur 1093:0): 
1.561     bisitz   1094:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                   1095:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1096:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1097:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1098:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1099:                   .&Apache::lonhtmlcommon::row_closure();
                   1100:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1101:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1102:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1103:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1104:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1105: 
1.442     banghart 1106:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1107:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1108:     $env{'form.Status'} = $saveStatus;
1.596.2.12.2.  1(raebur 1109:0):     my %optiontext = &Apache::lonlocal::texthash (
                   1110:0):                           lastonly => 'last submission',
                   1111:0):                           last     => 'last submission with details',
                   1112:0):                           datesub  => 'all submissions',
                   1113:0):                           all      => 'all submissions with details',
                   1114:0):                       );
                   1115:0):     my $submission_options =
1.592     bisitz   1116:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1117:0):         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
                   1118:0):         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1119:         '<span class="LC_nobreak">'.
                   1120:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.596.2.12.2.  1(raebur 1121:0):         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1122:         '<span class="LC_nobreak">'.
1.596.2.12.2.  1(raebur 1123:0):         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
                   1124:0):         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1125:         '<span class="LC_nobreak">'.
                   1126:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.596.2.12.2.  1(raebur 1127:0):         $optiontext{'all'}.'</label></span>';
                   1128:0):     my ($compmsg,$nocompmsg);
                   1129:0):     $nocompmsg = ' checked="checked"';
                   1130:0):     if ($numessay) {
                   1131:0):         $compmsg = $nocompmsg;
                   1132:0):         $nocompmsg = '';
                   1133:0):     }
1.561     bisitz   1134:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                   1135:                   .$submission_options
1.596.2.12.2.  1(raebur 1136:0):                   .&Apache::lonhtmlcommon::row_closure()
                   1137:0):                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
                   1138:0):                   .'<span class="LC_nobreak">'
                   1139:0):                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
                   1140:0):                   .&mt('No').('&nbsp;'x2).'</label>'
                   1141:0):                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
                   1142:0):                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1143:                   .&Apache::lonhtmlcommon::row_closure();
                   1144: 
                   1145:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1146:                   .'<select name="increment">'
                   1147:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1148:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1149:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1150:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.596.2.12.2.  1(raebur 1151:0):                   .'</select>';
1.485     albertel 1152:     $gradeTable .= 
1.432     banghart 1153:         &build_section_inputs().
1.45      ng       1154: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1155: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1156: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.596.2.12.2.  1(raebur 1157:0):     if (exists($env{'form.Status'})) {
1.561     bisitz   1158: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1159:     } else {
1.596.2.12.2.  1(raebur 1160:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1161:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1162:                       .&Apache::lonhtmlcommon::StatusOptions(
1.596.2.12.2.  1(raebur 1163:0):                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1164:     }
1.596.2.12.2.  1(raebur 1165:0):     if ($numessay) {
                   1166:0):         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
                   1167:0):                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1168:0):                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
                   1169:0):     }
                   1170:0):     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
1.561     bisitz   1171:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1172: 
                   1173:     $gradeTable .= '<p>'
1.596.2.12.2.  1(raebur 1174: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   1175:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1176:                   .'</p>';
1.249     albertel 1177: 
                   1178: # checkall buttons
                   1179:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1180:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1181:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1182:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1183:     $gradeTable.=&check_buttons();
1.450     banghart 1184:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1185:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1186: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1187:     my $loop = 0;
                   1188:     while ($loop < 2) {
1.485     albertel 1189: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1190: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.596.2.12.2.  1(raebur 1191:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1192: 	    foreach my $part (sort(@$partlist)) {
                   1193: 		my $display_part=
                   1194: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1195: 		$gradeTable.=
                   1196: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1197: 	    }
1.301     albertel 1198: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1199: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1200: 	}
                   1201: 	$loop++;
1.126     ng       1202: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1203:     }
1.474     albertel 1204:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1205: 
1.45      ng       1206:     my $ctr = 0;
1.294     albertel 1207:     foreach my $student (sort 
                   1208: 			 {
                   1209: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1210: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1211: 			     }
                   1212: 			     return $a cmp $b;
                   1213: 			 }
                   1214: 			 (keys(%$fullname))) {
1.41      ng       1215: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1216: 
1.110     ng       1217: 	my %status = ();
1.301     albertel 1218: 
                   1219: 	if ($submitonly eq 'queued') {
                   1220: 	    my %queue_status = 
                   1221: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1222: 							$udom,$uname);
                   1223: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1224: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1225: 	}
                   1226: 
1.596.2.12.2.  1(raebur 1227:0): 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1228: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1229: 	    my $submitted = 0;
1.164     albertel 1230: 	    my $graded = 0;
1.248     albertel 1231: 	    my $incorrect = 0;
1.110     ng       1232: 	    foreach (keys(%status)) {
1.145     albertel 1233: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1234: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1235: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1236: 		
1.110     ng       1237: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1238: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1239: 		    $submitted = 0;
1.150     albertel 1240: 		    my ($part)=split(/\./,$partid);
1.110     ng       1241: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1242: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1243: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1244: 		}
1.41      ng       1245: 	    }
1.248     albertel 1246: 	    
1.156     albertel 1247: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1248: 				     $submitonly eq 'incorrect' ||
                   1249: 				     $submitonly eq 'graded'));
1.248     albertel 1250: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1251: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1252: 	}
1.34      ng       1253: 
1.45      ng       1254: 	$ctr++;
1.249     albertel 1255: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1256:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1257: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1258: 	    if ($ctr%2 ==1) {
                   1259: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1260: 	    }
1.126     ng       1261: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1262:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1263:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1264: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1265: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1266: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1267: 
1.596.2.12.2.  1(raebur 1268:0): 	    if ($submitonly ne 'all') {
1.524     raeburn  1269: 		foreach (sort(keys(%status))) {
1.485     albertel 1270: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1271: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1272: 		}
1.41      ng       1273: 	    }
1.126     ng       1274: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1275: 	    if ($ctr%2 ==0) {
                   1276: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1277: 	    }
1.41      ng       1278: 	}
                   1279:     }
1.110     ng       1280:     if ($ctr%2 ==1) {
1.126     ng       1281: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.596.2.12.2.  1(raebur 1282:0): 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1283: 		foreach (@$partlist) {
                   1284: 		    $gradeTable.='<td>&nbsp;</td>';
                   1285: 		}
1.301     albertel 1286: 	    } elsif ($submitonly eq 'queued') {
                   1287: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1288: 	    }
1.474     albertel 1289: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1290:     }
                   1291: 
1.474     albertel 1292:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1293:         '<input type="button" '.
                   1294:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1295:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1296:     if ($ctr == 0) {
1.96      albertel 1297: 	my $num_students=(scalar(keys(%$fullname)));
                   1298: 	if ($num_students eq 0) {
1.485     albertel 1299: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1300: 	} else {
1.171     albertel 1301: 	    my $submissions='submissions';
                   1302: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1303: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1304: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1305: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1306:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1307: 		    $num_students).
                   1308: 		'</span><br />';
1.96      albertel 1309: 	}
1.46      ng       1310:     } elsif ($ctr == 1) {
1.474     albertel 1311: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1312:     }
                   1313:     $request->print($gradeTable);
1.44      ng       1314:     return '';
1.10      ng       1315: }
                   1316: 
1.44      ng       1317: #---- Called from the listStudents routine
1.249     albertel 1318: 
                   1319: sub check_script {
1.596.2.12.2.  1(raebur 1320:0):     my ($form,$type) = @_;
                   1321:0):     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1322:     function checkall() {
                   1323:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1324:             ele = document.forms.'.$form.'.elements[i];
                   1325:             if (ele.name == "'.$type.'") {
                   1326:             document.forms.'.$form.'.elements[i].checked=true;
                   1327:                                        }
                   1328:         }
                   1329:     }
                   1330: 
                   1331:     function checksec() {
                   1332:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1333:             ele = document.forms.'.$form.'.elements[i];
                   1334:            string = document.forms.'.$form.'.chksec.value;
                   1335:            if
                   1336:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1337:               document.forms.'.$form.'.elements[i].checked=true;
                   1338:             }
                   1339:         }
                   1340:     }
                   1341: 
                   1342: 
                   1343:     function uncheckall() {
                   1344:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1345:             ele = document.forms.'.$form.'.elements[i];
                   1346:             if (ele.name == "'.$type.'") {
                   1347:             document.forms.'.$form.'.elements[i].checked=false;
                   1348:                                        }
                   1349:         }
                   1350:     }
                   1351: 
1.596.2.12.2.  1(raebur 1352:0): '."\n");
1.249     albertel 1353:     return $chkallscript;
                   1354: }
                   1355: 
                   1356: sub check_buttons {
1.485     albertel 1357:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1358:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1359:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1360:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1361:     return $buttons;
                   1362: }
                   1363: 
1.44      ng       1364: #     Displays the submissions for one student or a group of students
1.34      ng       1365: sub processGroup {
1.596.2.12.2.  1(raebur 1366:0):     my ($request,$symb) = @_;
1.41      ng       1367:     my $ctr        = 0;
1.155     albertel 1368:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1369:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1370: 
1.396     banghart 1371:     foreach my $student (@stuchecked) {
                   1372: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1373: 	$env{'form.student'}        = $uname;
                   1374: 	$env{'form.userdom'}        = $udom;
                   1375: 	$env{'form.fullname'}       = $fullname;
1.596.2.12.2.  1(raebur 1376:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       1377: 	$ctr++;
                   1378:     }
                   1379:     return '';
1.35      ng       1380: }
1.34      ng       1381: 
1.44      ng       1382: #------------------------------------------------------------------------------------
                   1383: #
                   1384: #-------------------------- Next few routines handles grading by student, essentially
                   1385: #                           handles essay response type problem/part
                   1386: #
                   1387: #--- Javascript to handle the submission page functionality ---
                   1388: sub sub_page_js {
                   1389:     my $request = shift;
1.596.2.12.2.  6(raebur 1390:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1391:6):     &js_escape(\$alertmsg);
          1(raebur 1392:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1393:     function updateRadio(formname,id,weight) {
1.125     ng       1394: 	var gradeBox = formname["GD_BOX"+id];
                   1395: 	var radioButton = formname["RADVAL"+id];
                   1396: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1397: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1398: 	gradeBox.value = pts;
                   1399: 	var resetbox = false;
                   1400: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1401: 	    alert("$alertmsg"+pts);
1.71      ng       1402: 	    for (var i=0; i<radioButton.length; i++) {
                   1403: 		if (radioButton[i].checked) {
                   1404: 		    gradeBox.value = i;
                   1405: 		    resetbox = true;
                   1406: 		}
                   1407: 	    }
                   1408: 	    if (!resetbox) {
                   1409: 		formtextbox.value = "";
                   1410: 	    }
                   1411: 	    return;
1.44      ng       1412: 	}
1.71      ng       1413: 
                   1414: 	if (pts > weight) {
                   1415: 	    var resp = confirm("You entered a value ("+pts+
                   1416: 			       ") greater than the weight for the part. Accept?");
                   1417: 	    if (resp == false) {
1.125     ng       1418: 		gradeBox.value = oldpts;
1.71      ng       1419: 		return;
                   1420: 	    }
1.44      ng       1421: 	}
1.13      albertel 1422: 
1.71      ng       1423: 	for (var i=0; i<radioButton.length; i++) {
                   1424: 	    radioButton[i].checked=false;
                   1425: 	    if (pts == i && pts != "") {
                   1426: 		radioButton[i].checked=true;
                   1427: 	    }
                   1428: 	}
                   1429: 	updateSelect(formname,id);
1.125     ng       1430: 	formname["stores"+id].value = "0";
1.41      ng       1431:     }
1.5       albertel 1432: 
1.72      ng       1433:     function writeBox(formname,id,pts) {
1.125     ng       1434: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1435: 	if (checkSolved(formname,id) == 'update') {
                   1436: 	    gradeBox.value = pts;
                   1437: 	} else {
1.125     ng       1438: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1439: 	    gradeBox.value = oldpts;
1.125     ng       1440: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1441: 	    for (var i=0; i<radioButton.length; i++) {
                   1442: 		radioButton[i].checked=false;
1.72      ng       1443: 		if (i == oldpts) {
1.71      ng       1444: 		    radioButton[i].checked=true;
                   1445: 		}
                   1446: 	    }
1.41      ng       1447: 	}
1.125     ng       1448: 	formname["stores"+id].value = "0";
1.71      ng       1449: 	updateSelect(formname,id);
                   1450: 	return;
1.41      ng       1451:     }
1.44      ng       1452: 
1.71      ng       1453:     function clearRadBox(formname,id) {
                   1454: 	if (checkSolved(formname,id) == 'noupdate') {
                   1455: 	    updateSelect(formname,id);
                   1456: 	    return;
                   1457: 	}
1.125     ng       1458: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1459: 	for (var i=0; i<gradeSelect.length; i++) {
                   1460: 	    if (gradeSelect[i].selected) {
                   1461: 		var selectx=i;
                   1462: 	    }
                   1463: 	}
1.125     ng       1464: 	var stores = formname["stores"+id];
1.71      ng       1465: 	if (selectx == stores.value) { return };
1.125     ng       1466: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1467: 	gradeBox.value = "";
1.125     ng       1468: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1469: 	for (var i=0; i<radioButton.length; i++) {
                   1470: 	    radioButton[i].checked=false;
                   1471: 	}
                   1472: 	stores.value = selectx;
                   1473:     }
1.5       albertel 1474: 
1.71      ng       1475:     function checkSolved(formname,id) {
1.125     ng       1476: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1477: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1478: 	    if (!reply) {return "noupdate";}
1.120     ng       1479: 	    formname.overRideScore.value = 'yes';
1.41      ng       1480: 	}
1.71      ng       1481: 	return "update";
1.13      albertel 1482:     }
1.71      ng       1483: 
                   1484:     function updateSelect(formname,id) {
1.125     ng       1485: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1486: 	return;
1.41      ng       1487:     }
1.33      ng       1488: 
1.121     ng       1489: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1490:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1491: 	formname.gradeOpt.value = val;
1.71      ng       1492: 	if (val == "Save & Next") {
                   1493: 	    for (i=0;i<=total;i++) {
                   1494: 		for (j=0;j<parttot;j++) {
1.125     ng       1495: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1496: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1497: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1498: 			if (points == "") {
1.125     ng       1499: 			    var name = formname["name"+i].value;
1.129     ng       1500: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1501: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1502: 					       ", part "+partid+". Continue?");
1.71      ng       1503: 			    if (resp == false) {
1.125     ng       1504: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1505: 				return false;
                   1506: 			    }
                   1507: 			}
                   1508: 		    }
                   1509: 		}
                   1510: 	    }
                   1511: 	}
1.120     ng       1512: 	formname.submit();
                   1513:     }
                   1514: 
1.71      ng       1515: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1516:     function checkSubmitPage(formname,total) {
                   1517: 	noscore = new Array(100);
                   1518: 	var ptr = 0;
                   1519: 	for (i=1;i<total;i++) {
1.125     ng       1520: 	    var partid = formname["q_"+i].value;
1.127     ng       1521: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1522: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1523: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1524: 		if (points == "" && status != "correct_by_student") {
                   1525: 		    noscore[ptr] = i;
                   1526: 		    ptr++;
                   1527: 		}
                   1528: 	    }
                   1529: 	}
                   1530: 	if (ptr != 0) {
                   1531: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1532: 	    var prolist = "";
                   1533: 	    if (ptr == 1) {
                   1534: 		prolist = noscore[0];
                   1535: 	    } else {
                   1536: 		var i = 0;
                   1537: 		while (i < ptr-1) {
                   1538: 		    prolist += noscore[i]+", ";
                   1539: 		    i++;
                   1540: 		}
                   1541: 		prolist += "and "+noscore[i];
                   1542: 	    }
                   1543: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1544: 	    if (resp == false) {
                   1545: 		return false;
                   1546: 	    }
                   1547: 	}
1.45      ng       1548: 
1.71      ng       1549: 	formname.submit();
                   1550:     }
                   1551: SUBJAVASCRIPT
                   1552: }
1.45      ng       1553: 
1.596.2.12.2.  1(raebur 1554:0): #--- javascript for grading message center
                   1555:0): sub sub_grademessage_js {
1.71      ng       1556:     my $request = shift;
1.80      ng       1557:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1558:     &commonJSfunctions($request);
1.350     albertel 1559: 
1.596.2.12.2.  1(raebur 1560:0):     my $inner_js_msg_central= (<<INNERJS);
                   1561:0): <script type="text/javascript">
1.350     albertel 1562:     function checkInput() {
                   1563:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1564:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1565:       var usrctr = document.msgcenter.usrctr.value;
                   1566:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1567:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1568: 
                   1569:       var msgchk = "";
                   1570:       if (document.msgcenter.subchk.checked) {
                   1571:          msgchk = "msgsub,";
                   1572:       }
                   1573:       var includemsg = 0;
                   1574:       for (var i=1; i<=nmsg; i++) {
                   1575:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1576:           var frmmsg = document.msgcenter["msg"+i];
                   1577:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1578:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1579:           showflg.value = "1";
                   1580:           var chkbox = document.msgcenter["msgn"+i];
                   1581:           if (chkbox.checked) {
                   1582:              msgchk += "savemsg"+i+",";
                   1583:              includemsg = 1;
                   1584:           }
                   1585:       }
                   1586:       if (document.msgcenter.newmsgchk.checked) {
                   1587:          msgchk += "newmsg"+usrctr;
                   1588:          includemsg = 1;
                   1589:       }
                   1590:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1591:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1592:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1593:       includemsg.value = msgchk;
                   1594: 
                   1595:       self.close()
                   1596: 
                   1597:     }
1.351     albertel 1598: </script>
                   1599: INNERJS
                   1600: 
1.596.2.12.2.  1(raebur 1601:0):     my $start_page_msg_central =
1.351     albertel 1602:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1603: 				       {'js_ready'  => 1,
                   1604: 					'only_body' => 1,
                   1605: 					'bgcolor'   =>'#FFFFFF',});
1.596.2.12.2.  1(raebur 1606:0):     my $end_page_msg_central =
1.351     albertel 1607: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1608: 
                   1609: 
1.219     www      1610:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1611:     $docopen=~s/^document\.//;
1.596.2.12.2.  1(raebur 1612:0): 
          6(raebur 1613:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1614:                 comp => 'Compose Message for: ',
                   1615:                 incl => 'Include',
                   1616:                 type => 'Type',
                   1617:                 subj => 'Subject',
                   1618:                 mesa => 'Message',
                   1619:                 new  => 'New',
                   1620:                 save => 'Save',
                   1621:                 canc => 'Cancel',
                   1622:              );
1.596.2.12.2.  6(raebur 1623:6):     &html_escape(\%html_js_lt);
                   1624:6):     &js_escape(\%html_js_lt);
          1(raebur 1625:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.44      ng       1626: 
                   1627: //===================== Script to view submitted by ==================
                   1628:   function viewSubmitter(submitter) {
                   1629:     document.SCORE.refresh.value = "on";
                   1630:     document.SCORE.NCT.value = "1";
                   1631:     document.SCORE.unamedom0.value = submitter;
                   1632:     document.SCORE.submit();
                   1633:     return;
                   1634:   }
                   1635: 
                   1636: //====================== Script for composing message ==============
1.80      ng       1637:    // preload images
                   1638:    img1 = new Image();
                   1639:    img1.src = "$iconpath/mailbkgrd.gif";
                   1640:    img2 = new Image();
                   1641:    img2.src = "$iconpath/mailto.gif";
                   1642: 
1.44      ng       1643:   function msgCenter(msgform,usrctr,fullname) {
                   1644:     var Nmsg  = msgform.savemsgN.value;
                   1645:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1646:     var subject = msgform.msgsub.value;
1.127     ng       1647:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1648:     re = /msgsub/;
                   1649:     var shwsel = "";
                   1650:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1651:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1652:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1653:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1654: 	var testmsg = "savemsg"+i+",";
                   1655: 	re = new RegExp(testmsg,"g");
1.44      ng       1656: 	shwsel = "";
                   1657: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1658: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1659: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1660: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1661: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1662:     }
1.125     ng       1663:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1664:     shwsel = "";
                   1665:     re = /newmsg/;
                   1666:     if (re.test(msgchk)) { shwsel = "checked" }
                   1667:     newMsg(newmsg,shwsel);
                   1668:     msgTail(); 
                   1669:     return;
                   1670:   }
                   1671: 
1.123     ng       1672:   function checkEntities(strx) {
                   1673:     if (strx.length == 0) return strx;
                   1674:     var orgStr = ["&", "<", ">", '"']; 
                   1675:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1676:     var counter = 0;
                   1677:     while (counter < 4) {
                   1678: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1679: 	counter++;
                   1680:     }
                   1681:     return strx;
                   1682:   }
                   1683: 
                   1684:   function strReplace(strx, orgStr, newStr) {
                   1685:     return strx.split(orgStr).join(newStr);
                   1686:   }
                   1687: 
1.44      ng       1688:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1689:     var height = 70*Nmsg+250;
1.44      ng       1690:     if (height > 600) {
                   1691: 	height = 600;
                   1692:     }
1.118     ng       1693:     var xpos = (screen.width-600)/2;
                   1694:     xpos = (xpos < 0) ? '0' : xpos;
                   1695:     var ypos = (screen.height-height)/2-30;
                   1696:     ypos = (ypos < 0) ? '0' : ypos;
                   1697: 
1.596.2.12.2.  (raeburn 1698:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1699:     pWin.focus();
                   1700:     pDoc = pWin.document;
1.219     www      1701:     pDoc.$docopen;
1.351     albertel 1702:     pDoc.write('$start_page_msg_central');
1.76      ng       1703: 
                   1704:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1705:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  1(raebur 1706:0):     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1707: 
1.596.2.12.2.  1(raebur 1708:0):     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1709: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       1710: }
                   1711:     function displaySubject(msg,shwsel) {
1.76      ng       1712:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1713:0):     pDoc.write("<tr>");
1.465     albertel 1714:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1715:0):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
                   1716:0):     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1717: }
                   1718: 
1.72      ng       1719:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1720:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1721:0):     pDoc.write("<tr>");
1.465     albertel 1722:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1723:0):     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1.465     albertel 1724:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1725: }
                   1726: 
                   1727:   function newMsg(newmsg,shwsel) {
1.76      ng       1728:     pDoc = pWin.document;
1.596.2.12.2.  1(raebur 1729:0):     pDoc.write("<tr>");
1.465     albertel 1730:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.596.2.12.2.  1(raebur 1731:0):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1732:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1733: }
                   1734: 
                   1735:   function msgTail() {
1.76      ng       1736:     pDoc = pWin.document;
1.465     albertel 1737:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1738:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1739:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1740:     pDoc.write("<\\/form>");
1.351     albertel 1741:     pDoc.write('$end_page_msg_central');
1.128     ng       1742:     pDoc.close();
1.44      ng       1743: }
                   1744: 
1.596.2.12.2.  1(raebur 1745:0): SUBJAVASCRIPT
                   1746:0): }
                   1747:0): 
                   1748:0): #--- javascript for essay type problem --
                   1749:0): sub sub_page_kw_js {
                   1750:0):     my $request = shift;
                   1751:0): 
                   1752:0):     unless ($env{'form.compmsg'}) {
                   1753:0):         &commonJSfunctions($request);
                   1754:0):     }
                   1755:0): 
                   1756:0):     my $inner_js_highlight_central= (<<INNERJS);
                   1757:0): <script type="text/javascript">
                   1758:0):     function updateChoice(flag) {
                   1759:0):       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1760:0):       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1761:0):       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1762:0):       opener.document.SCORE.refresh.value = "on";
                   1763:0):       if (opener.document.SCORE.keywords.value!=""){
                   1764:0):          opener.document.SCORE.submit();
                   1765:0):       }
                   1766:0):       self.close()
                   1767:0):     }
                   1768:0): </script>
                   1769:0): INNERJS
                   1770:0): 
                   1771:0):     my $start_page_highlight_central =
                   1772:0):         &Apache::loncommon::start_page('Highlight Central',
                   1773:0):                                        $inner_js_highlight_central,
                   1774:0):                                        {'js_ready'  => 1,
                   1775:0):                                         'only_body' => 1,
                   1776:0):                                         'bgcolor'   =>'#FFFFFF',});
                   1777:0):     my $end_page_highlight_central =
                   1778:0):         &Apache::loncommon::end_page({'js_ready' => 1});
                   1779:0): 
                   1780:0):     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1781:0):     $docopen=~s/^document\.//;
                   1782:0): 
                   1783:0):     my %js_lt = &Apache::lonlocal::texthash(
                   1784:0):                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1785:0):                 plse => 'Please select a word or group of words from document and then click this link.',
                   1786:0):                 adds => 'Add selection to keyword list? Edit if desired.',
                   1787:0):                 col1 => 'red',
                   1788:0):                 col2 => 'green',
                   1789:0):                 col3 => 'blue',
                   1790:0):                 siz1 => 'normal',
                   1791:0):                 siz2 => '+1',
                   1792:0):                 siz3 => '+2',
                   1793:0):                 sty1 => 'normal',
                   1794:0):                 sty2 => 'italic',
                   1795:0):                 sty3 => 'bold',
                   1796:0):              );
                   1797:0):     my %html_js_lt = &Apache::lonlocal::texthash(
                   1798:0):                 save => 'Save',
                   1799:0):                 canc => 'Cancel',
                   1800:0):                 kehi => 'Keyword Highlight Options',
                   1801:0):                 txtc => 'Text Color',
                   1802:0):                 font => 'Font Size',
                   1803:0):                 fnst => 'Font Style',
                   1804:0):              );
                   1805:0):     &js_escape(\%js_lt);
                   1806:0):     &html_escape(\%html_js_lt);
                   1807:0):     &js_escape(\%html_js_lt);
                   1808:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
                   1809:0): 
                   1810:0): //===================== Show list of keywords ====================
                   1811:0):   function keywords(formname) {
                   1812:0):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
                   1813:0):     if (nret==null) return;
                   1814:0):     formname.keywords.value = nret;
                   1815:0): 
                   1816:0):     if (formname.keywords.value != "") {
                   1817:0):         formname.refresh.value = "on";
                   1818:0):         formname.submit();
                   1819:0):     }
                   1820:0):     return;
                   1821:0):   }
                   1822:0): 
                   1823:0): //===================== Script to add keyword(s) ==================
                   1824:0):   function getSel() {
                   1825:0):     if (document.getSelection) txt = document.getSelection();
                   1826:0):     else if (document.selection) txt = document.selection.createRange().text;
                   1827:0):     else return;
                   1828:0):     if (typeof(txt) != 'string') {
                   1829:0):         txt = String(txt);
                   1830:0):     }
                   1831:0):     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1832:0):     if (cleantxt=="") {
                   1833:0):         alert("$js_lt{'plse'}");
                   1834:0):         return;
                   1835:0):     }
                   1836:0):     var nret = prompt("$js_lt{'adds'}",cleantxt);
                   1837:0):     if (nret==null) return;
                   1838:0):     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
                   1839:0):     if (document.SCORE.keywords.value != "") {
                   1840:0):         document.SCORE.refresh.value = "on";
                   1841:0):         document.SCORE.submit();
                   1842:0):     }
                   1843:0):     return;
                   1844:0):   }
                   1845:0): 
1.44      ng       1846: //====================== Script for keyword highlight options ==============
                   1847:   function kwhighlight() {
                   1848:     var kwclr    = document.SCORE.kwclr.value;
                   1849:     var kwsize   = document.SCORE.kwsize.value;
                   1850:     var kwstyle  = document.SCORE.kwstyle.value;
                   1851:     var redsel = "";
                   1852:     var grnsel = "";
                   1853:     var blusel = "";
1.596.2.12.2.  6(raebur 1854:6):     var txtcol1 = "$js_lt{'col1'}";
                   1855:6):     var txtcol2 = "$js_lt{'col2'}";
                   1856:6):     var txtcol3 = "$js_lt{'col3'}";
                   1857:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1858:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1859:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1860:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1861:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1862:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1863:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1864:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1865:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1866:     var sznsel = "";
                   1867:     var sz1sel = "";
                   1868:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1869:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1870:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1871:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1872:     var synsel = "";
                   1873:     var syisel = "";
                   1874:     var sybsel = "";
1.596.2.12.2.  8(raebur 1875:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1876:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1877:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1878:     highlightCentral();
1.596.2.12.2.  8(raebur 1879:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1880:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1881:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1882:     highlightend();
                   1883:     return;
                   1884:   }
                   1885: 
                   1886:   function highlightCentral() {
1.76      ng       1887: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1888:     var xpos = (screen.width-400)/2;
                   1889:     xpos = (xpos < 0) ? '0' : xpos;
                   1890:     var ypos = (screen.height-330)/2-30;
                   1891:     ypos = (ypos < 0) ? '0' : ypos;
                   1892: 
1.206     albertel 1893:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1894:     hwdWin.focus();
                   1895:     var hDoc = hwdWin.document;
1.219     www      1896:     hDoc.$docopen;
1.351     albertel 1897:     hDoc.write('$start_page_highlight_central');
1.76      ng       1898:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1899:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1900: 
1.596.2.12.2.  8(raebur 1901:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1902: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       1903:   }
                   1904: 
                   1905:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1906:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1907:4):     hDoc.write("<tr>");
1.76      ng       1908:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1909:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1910:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1911:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1912:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1913:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1914:     hDoc.write("<\\/tr>");
1.44      ng       1915:   }
                   1916: 
                   1917:   function highlightend() { 
1.76      ng       1918:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1919:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1920:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1921:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1922:     hDoc.write("<\\/form>");
1.351     albertel 1923:     hDoc.write('$end_page_highlight_central');
1.128     ng       1924:     hDoc.close();
1.44      ng       1925:   }
                   1926: 
                   1927: SUBJAVASCRIPT
                   1928: }
                   1929: 
1.349     albertel 1930: sub get_increment {
1.348     bowersj2 1931:     my $increment = $env{'form.increment'};
                   1932:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1933:         $increment != .1) {
                   1934:         $increment = 1;
                   1935:     }
                   1936:     return $increment;
                   1937: }
                   1938: 
1.585     bisitz   1939: sub gradeBox_start {
                   1940:     return (
                   1941:         &Apache::loncommon::start_data_table()
                   1942:        .&Apache::loncommon::start_data_table_header_row()
                   1943:        .'<th>'.&mt('Part').'</th>'
                   1944:        .'<th>'.&mt('Points').'</th>'
                   1945:        .'<th>&nbsp;</th>'
                   1946:        .'<th>'.&mt('Assign Grade').'</th>'
                   1947:        .'<th>'.&mt('Weight').'</th>'
                   1948:        .'<th>'.&mt('Grade Status').'</th>'
                   1949:        .&Apache::loncommon::end_data_table_header_row()
                   1950:     );
                   1951: }
                   1952: 
                   1953: sub gradeBox_end {
                   1954:     return (
                   1955:         &Apache::loncommon::end_data_table()
                   1956:     );
                   1957: }
1.71      ng       1958: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1959: sub gradeBox {
1.322     albertel 1960:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1961:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1962: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1963:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1964:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1965:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1966:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1967:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1968: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1969:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1970:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1971:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1972: 				       [$partid]);
                   1973:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1974:     if ($last_resets{$partid}) {
                   1975:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1976:     }
1.596.2.12.2.  8(raebur 1977:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1978:     my $ctr = 0;
1.348     bowersj2 1979:     my $thisweight = 0;
1.349     albertel 1980:     my $increment = &get_increment();
1.485     albertel 1981: 
                   1982:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1983:     while ($thisweight<=$wgt) {
1.532     bisitz   1984: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1985:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1986: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1987: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1988: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1989:         $thisweight += $increment;
1.71      ng       1990: 	$ctr++;
                   1991:     }
1.485     albertel 1992:     $radio.='</tr></table>';
                   1993: 
                   1994:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1995: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1996: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1997: 	$wgt.')" /></td>'."\n";
1.485     albertel 1998:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1999: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2000: 	' </td>'."\n";
                   2001:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2002: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2003:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2004: 	$line.='<option></option>'.
                   2005: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2006:     } else {
1.485     albertel 2007: 	$line.='<option selected="selected"></option>'.
                   2008: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2009:     }
1.485     albertel 2010:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2011: 
                   2012: 
                   2013:     $result .= 
1.596.2.12.2.  8(raebur 2014:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
          1(raebur 2015:0):     $result.=&Apache::loncommon::end_data_table_row();
                   2016:0):     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2017:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2018: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2019: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2020: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2021:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2022:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2023:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2024:         $aggtries.'" />'."\n";
1.582     raeburn  2025:     my $res_error;
                   2026:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 2027:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2028:     if ($res_error) {
                   2029:         return &navmap_errormsg();
                   2030:     }
1.318     banghart 2031:     return $result;
                   2032: }
1.322     albertel 2033: 
                   2034: sub handback_box {
1.596.2.12.2.  1(raebur 2035:0):     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   2036:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
                   2037:0):     return unless ($numessay);
1.323     banghart 2038:     my (@respids);
1.596.2.4  raeburn  2039:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2040:     foreach my $part_response_id (@part_response_id) {
                   2041:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2042:         if ($part eq $partid) {
1.375     albertel 2043:             push(@respids,$resp);
1.323     banghart 2044:         }
                   2045:     }
1.318     banghart 2046:     my $result;
1.323     banghart 2047:     foreach my $respid (@respids) {
1.322     albertel 2048: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2049: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2050: 	next if (!@$files);
1.596.2.4  raeburn  2051: 	my $file_counter = 0;
1.313     banghart 2052: 	foreach my $file (@$files) {
1.368     banghart 2053: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  2054:                 $file_counter++;
1.368     banghart 2055:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   2056:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   2057:     	        $file_disp = "$name.$ext";
                   2058:     	        $file = $file_path.$file_disp;
                   2059:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2060:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2061:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  2062:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2063: 	    }
1.322     albertel 2064: 	}
1.596.2.4  raeburn  2065:         if ($file_counter) {
                   2066:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2067:                        '<span class="LC_info">'.
                   2068:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2069:         }
1.313     banghart 2070:     }
1.318     banghart 2071:     return $result;    
1.71      ng       2072: }
1.44      ng       2073: 
1.58      albertel 2074: sub show_problem {
1.382     albertel 2075:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2076:     my $rendered;
1.382     albertel 2077:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2078:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2079:     if ($mode eq 'both' or $mode eq 'text') {
                   2080: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2081: 						       $env{'request.course.id'},
                   2082: 						       undef,\%form);
1.144     albertel 2083:     }
1.58      albertel 2084:     if ($removeform) {
                   2085: 	$rendered=~s|<form(.*?)>||g;
                   2086: 	$rendered=~s|</form>||g;
1.374     albertel 2087: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2088:     }
1.144     albertel 2089:     my $companswer;
                   2090:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2091: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2092: 	$companswer=
                   2093: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2094: 						    $env{'request.course.id'},
                   2095: 						    %form);
1.144     albertel 2096:     }
1.58      albertel 2097:     if ($removeform) {
                   2098: 	$companswer=~s|<form(.*?)>||g;
                   2099: 	$companswer=~s|</form>||g;
1.144     albertel 2100: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2101:     }
1.596.2.12.2.  (raeburn 2102:):     my $renderheading = &mt('View of the problem');
                   2103:):     my $answerheading = &mt('Correct answer');
                   2104:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2105:):         my $stu_fullname = $env{'form.fullname'};
                   2106:):         if ($stu_fullname eq '') {
                   2107:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2108:):         }
                   2109:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2110:):         if ($forwhom ne '') {
                   2111:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2112:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2113:):         }
                   2114:):     }
1.468     albertel 2115:     $rendered=
1.588     bisitz   2116:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2117:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2118:        .$rendered
                   2119:        .'</div>';
1.468     albertel 2120:     $companswer=
1.588     bisitz   2121:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 2122:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2123:        .$companswer
                   2124:        .'</div>';
1.468     albertel 2125:     my $result;
1.144     albertel 2126:     if ($mode eq 'both') {
1.588     bisitz   2127:         $result=$rendered.$companswer;
1.144     albertel 2128:     } elsif ($mode eq 'text') {
1.588     bisitz   2129:         $result=$rendered;
1.144     albertel 2130:     } elsif ($mode eq 'answer') {
1.588     bisitz   2131:         $result=$companswer;
1.144     albertel 2132:     }
1.71      ng       2133:     return $result;
1.58      albertel 2134: }
1.397     albertel 2135: 
1.396     banghart 2136: sub files_exist {
                   2137:     my ($r, $symb) = @_;
                   2138:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2139:     foreach my $student (@students) {
                   2140:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2141:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2142: 					      $udom,$uname);
1.396     banghart 2143:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2144:         foreach my $submission (@$string) {
                   2145:             my ($partid,$respid) =
                   2146: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2147:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2148: 					   \%record);
                   2149:             return 1 if (@$files);
1.396     banghart 2150:         }
                   2151:     }
1.397     albertel 2152:     return 0;
1.396     banghart 2153: }
1.397     albertel 2154: 
1.394     banghart 2155: sub download_all_link {
                   2156:     my ($r,$symb) = @_;
1.596.2.12.2.  1(raebur 2157:0):     unless (&files_exist($r, $symb)) {
                   2158:0):         $r->print(&mt('There are currently no submitted documents.'));
                   2159:0):         return;
                   2160:0):     }
1.395     albertel 2161:     my $all_students = 
                   2162: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2163: 
                   2164:     my $parts =
                   2165: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2166: 
1.394     banghart 2167:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2168:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2169:                              'cgi.'.$identifier.'.symb' => $symb,
                   2170:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2171:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2172: 	      &mt('Download All Submitted Documents').'</a>');
1.596.2.12.2.  1(raebur 2173:0):     return;
                   2174:0): }
                   2175:0): 
                   2176:0): sub submit_download_link {
                   2177:0):     my ($request,$symb) = @_;
                   2178:0):     if (!$symb) { return ''; }
                   2179:0):     my $res_error;
                   2180:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   2181:0):         &response_type($symb,\$res_error);
                   2182:0):     if ($res_error) {
                   2183:0):         $request->print(&mt('An error occurred retrieving response types'));
                   2184:0):         return;
                   2185:0):     }
                   2186:0):     unless ($numessay) {
                   2187:0):         $request->print(&mt('No essayresponse items found'));
                   2188:0):         return;
                   2189:0):     }
                   2190:0):     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2191:0):     if (@chosenparts) {
                   2192:0):         $request->print(&showResourceInfo($symb,$partlist,$responseType,
                   2193:0):                                           undef,undef,1));
                   2194:0):     }
                   2195:0):     if ($numessay) {
                   2196:0):         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2197:0):         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2198:0):         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2199:0):         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2200:0):         if (ref($fullname) eq 'HASH') {
                   2201:0):             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2202:0):             if (@students) {
                   2203:0):                 @{$env{'form.stuinfo'}} = @students;
                   2204:0):                 if ($numdropbox) {
                   2205:0):                     &download_all_link($request,$symb);
                   2206:0):                 } else {
                   2207:0):                     $request->print(&mt('No essayrespose items with dropbox found'));
                   2208:0):                 }
                   2209:0): # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
                   2210:0): # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2211:0):             } else {
                   2212:0):                 $request->print(&mt('No students match the criteria you selected'));
                   2213:0):             }
                   2214:0):         } else {
                   2215:0):             $request->print(&mt('Could not retrieve student information'));
                   2216:0):         }
                   2217:0):     } else {
                   2218:0):         $request->print(&mt('No essayresponse items found'));
                   2219:0):     }
                   2220:0):     return;
1.394     banghart 2221: }
1.395     albertel 2222: 
1.432     banghart 2223: sub build_section_inputs {
                   2224:     my $section_inputs;
                   2225:     if ($env{'form.section'} eq '') {
                   2226:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2227:     } else {
                   2228:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2229:         foreach my $section (@sections) {
1.432     banghart 2230:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2231:         }
                   2232:     }
                   2233:     return $section_inputs;
                   2234: }
                   2235: 
1.44      ng       2236: # --------------------------- show submissions of a student, option to grade 
                   2237: sub submission {
1.596.2.12.2.  1(raebur 2238:0):     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2239:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2240:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2241:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2242:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  1(raebur 2243:0): 
1.324     albertel 2244:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.596.2.12.2.  1(raebur 2245:0):     my $probtitle=&Apache::lonnet::gettitle($symb);
          5(raebur 2246:9):     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2247: 
                   2248:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2249:4):         $request->print(
                   2250:4):             '<span class="LC_warning">'.
                   2251:4):             &mt('Unable to view requested student.').
                   2252:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2253:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2254:4):             '</span>');
1.104     albertel 2255: 	return;
                   2256:     }
                   2257: 
1.596.2.12.2.  1(raebur 2258:0):     my $res_error;
                   2259:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
                   2260:0):         &response_type($symb,\$res_error);
                   2261:0):     if ($res_error) {
                   2262:0):         $request->print(&navmap_errormsg());
                   2263:0):         return;
                   2264:0):     }
                   2265:0): 
1.257     albertel 2266:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2267:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2268:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1.596.2.12.2.  1(raebur 2269:0):     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
                   2270:0):         $env{'form.compmsg'} = 1;
                   2271:0):     }
1.257     albertel 2272:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2273:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2274: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2275: 	'/check.gif" height="16" border="0" />';
1.41      ng       2276: 
                   2277:     # header info
                   2278:     if ($counter == 0) {
1.596.2.12.2.  1(raebur 2279:0):         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
                   2280:0):         if (@chosenparts) {
                   2281:0):             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
                   2282:0):         } elsif ($divforres) {
                   2283:0):             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
                   2284:0):         } else {
                   2285:0):             $request->print('<br clear="all" />');
                   2286:0):         }
1.41      ng       2287: 	&sub_page_js($request);
1.596.2.12.2.  1(raebur 2288:0):         &sub_grademessage_js($request) if ($env{'form.compmsg'});
                   2289:0): 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2290: 
1.44      ng       2291: 	# option to display problem, only once else it cause problems 
                   2292:         # with the form later since the problem has a form.
1.257     albertel 2293: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2294: 	    my $mode;
1.257     albertel 2295: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2296: 		$mode='both';
1.257     albertel 2297: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2298: 		$mode='text';
1.257     albertel 2299: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2300: 		$mode='answer';
                   2301: 	    }
1.329     albertel 2302: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2303: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2304: 	}
1.441     www      2305: 
1.41      ng       2306: 	my %keyhash = ();
1.596.2.12.2.  1(raebur 2307:0): 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2308: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2309: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2310: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.596.2.12.2.  1(raebur 2311:0): 	}
                   2312:0): 	# kwclr is the only variable that is guaranteed not to be blank
                   2313:0): 	# if this subroutine has been called once.
                   2314:0): 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2315: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2316: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2317: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2318: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2319: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.596.2.12.2.  1(raebur 2320:0): 	}
                   2321:0): 	if ($env{'form.compmsg'}) {
                   2322:0): 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
                   2323:0): 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2324: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2325: 	}
1.596.2.12.2.  1(raebur 2326:0): 
1.257     albertel 2327: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2328: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2329: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2330: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2331: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2332: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2333: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2334: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2335: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2336: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2337: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2338: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2339: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2340:0): 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2341: 			&build_section_inputs().
1.326     albertel 2342: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2343: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2344: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.596.2.12.2.  1(raebur 2345:0): 	if ($env{'form.compmsg'}) {
                   2346:0): 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
                   2347:0): 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
                   2348:0): 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
                   2349:0): 	}
                   2350:0): 	if ($numessay) {
1.257     albertel 2351: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2352: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2353: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.596.2.12.2.  1(raebur 2354:0): 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2355: 	}
1.596.2.12.2.  1(raebur 2356:0): 
1.41      ng       2357: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2358: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2359: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2360: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2361: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2362: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2363: 		'" />'."\n".
                   2364: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2365: 	    $cts++;
                   2366: 	}
                   2367: 	$request->print($prnmsg);
1.32      ng       2368: 
1.596.2.12.2.  1(raebur 2369:0): 	if ($numessay) {
1.596.2.4  raeburn  2370: 
                   2371:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2372:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2373:                           keyw => 'Keyword Options',
                   2374:                           list => 'List',
                   2375:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2376:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2377:                      );
1.88      www      2378: #
                   2379: # Print out the keyword options line
                   2380: #
1.596.2.12.2.  1(raebur 2381:0): 	    $request->print(
          8(raebur 2382:4):                 '<div class="LC_columnSection">'
                   2383:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2384:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2385:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2386:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2387:4):  class="page">'.$lt{'past'}.'</a>',
                   2388:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2389:4):                     {legend => $lt{'keyw'}})
                   2390:4):                .'</fieldset></div>'
                   2391:4):             );
                   2392:4): 
1.88      www      2393: #
                   2394: # Load the other essays for similarity check
                   2395: #
1.596.2.12.2.  5(raebur 2396:9):             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2397:9):             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2398:9):                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2399:9):                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2400:9):                 if ($cdom ne '' && $cnum ne '') {
                   2401:9):                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2402:9):                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2403:9):                         my $apath = $1.'_'.$id;
                   2404:9):                         $apath=~s/\W/\_/gs;
                   2405:9):                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2406:9):                     }
                   2407:9):                 }
                   2408:9):             } else {
                   2409:9): 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2410:9): 	        $apath=&escape($apath);
                   2411:9): 	        $apath=~s/\W/\_/gs;
                   2412:9):                 &init_old_essays($symb,$apath,$adom,$aname);
                   2413:9):             }
1.41      ng       2414:         }
                   2415:     }
1.44      ng       2416: 
1.441     www      2417: # This is where output for one specific student would start
1.592     bisitz   2418:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2419:     $request->print(
                   2420:         "\n\n"
                   2421:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2422:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2423:        ."\n"
                   2424:     );
1.441     www      2425: 
1.592     bisitz   2426:     # Show additional functions if allowed
                   2427:     if ($perm{'vgr'}) {
                   2428:         $request->print(
                   2429:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2430:3):                 'View recent activity',
1.592     bisitz   2431:                 $uname,$udom,'check')
                   2432:            .' '
                   2433:         );
                   2434:     }
                   2435:     if ($perm{'opa'}) {
                   2436:         $request->print(
                   2437:             &Apache::loncommon::pprmlink(
                   2438:                 &mt('Set/Change parameters'),
                   2439:                 $uname,$udom,$symb,'check'));
                   2440:     }
                   2441: 
                   2442:     # Show Problem
1.257     albertel 2443:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2444: 	my $mode;
1.257     albertel 2445: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2446: 	    $mode='both';
1.257     albertel 2447: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2448: 	    $mode='text';
1.257     albertel 2449: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2450: 	    $mode='answer';
                   2451: 	}
1.329     albertel 2452: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2453: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2454:     }
1.144     albertel 2455: 
1.257     albertel 2456:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2457: 
1.44      ng       2458:     # Display student info
1.41      ng       2459:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2460: 
                   2461:     my $result='<div class="LC_Box">'
                   2462:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2463:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2464:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.596.2.12.2.  1(raebur 2465:0):     if ($numresp > $numessay) {
1.588     bisitz   2466:         $result.='<p class="LC_info">'
                   2467:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2468:                 ."</p>\n";
1.469     albertel 2469:     }
                   2470: 
1.596.2.12.2.  1(raebur 2471:0):     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2472:     my $fullname;
                   2473:     my $col_fullnames = [];
1.596.2.12.2.  1(raebur 2474:0):     if ($numessay) {
1.464     albertel 2475: 	(my $sub_result,$fullname,$col_fullnames)=
                   2476: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2477: 				 $counter);
                   2478: 	$result.=$sub_result;
1.41      ng       2479:     }
1.44      ng       2480:     $request->print($result."\n");
1.588     bisitz   2481: 
1.44      ng       2482:     # print student answer/submission
1.596.2.12.2.  1(raebur 2483:0):     # Options are (1) Last submission only
                   2484:0):     #             (2) Last submission (with detailed information for that submission)
                   2485:0):     #             (3) All transactions (by date)
                   2486:0):     #             (4) The whole record (with detailed information for all transactions)
                   2487:0): 
                   2488:0):     my ($string,$timestamp)= &get_last_submission(\%record);
                   2489:0): 
                   2490:0):     my $lastsubonly;
                   2491:0): 
                   2492:0):     if ($$timestamp eq '') {
                   2493:0):         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2494:0):     } else {
                   2495:0):         $lastsubonly =
                   2496:0):             '<div class="LC_grade_submissions_body">'
                   2497:0):            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2498:0): 
                   2499:0): 	my %seenparts;
                   2500:0): 	my @part_response_id = &flatten_responseType($responseType);
                   2501:0): 	foreach my $part (@part_response_id) {
                   2502:0): 	    my ($partid,$respid) = @{ $part };
                   2503:0): 	    my $display_part=&get_display_part($partid,$symb);
                   2504:0): 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2505:0): 		if (exists($seenparts{$partid})) { next; }
                   2506:0): 		$seenparts{$partid}=1;
                   2507:0):                 $request->print(
                   2508:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2509:0):                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2510:0):                                '<a href="javascript:viewSubmitter(\''.
                   2511:0):                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2512:0):                                '\');" target="_self">'.
                   2513:0):                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2514:0):                     '<br />');
                   2515:0): 		next;
                   2516:0): 	    }
                   2517:0): 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2518:0): 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2519:0):                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2520:0):                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2521:0):                     ' <span class="LC_internal_info">'.
                   2522:0):                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2523:0):                     '</span>&nbsp; &nbsp;'.
                   2524:0): 	            '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2525:0): 		next;
                   2526:0): 	    }
                   2527:0): 	    foreach my $submission (@$string) {
                   2528:0): 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2529:0): 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
                   2530:0): 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
                   2531:0): 		# Similarity check
                   2532:0):                 my $similar='';
                   2533:0):                 my ($type,$trial,$rndseed);
                   2534:0):                 if ($hide eq 'rand') {
                   2535:0):                     $type = 'randomizetry';
                   2536:0):                     $trial = $record{"resource.$partid.tries"};
                   2537:0):                     $rndseed = $record{"resource.$partid.rndseed"};
                   2538:0):                 }
                   2539:0): 		if ($env{'form.checkPlag'}) {
                   2540:0): 		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2541:0): 		        &most_similar($uname,$udom,$symb,$subval);
                   2542:0): 		    if ($osim) {
                   2543:0): 		        $osim=int($osim*100.0);
                   2544:0):                         if ($hide eq 'anon') {
                   2545:0):                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2546:0):                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2547:0):                         } else {
                   2548:0): 			    $similar='<hr />';
                   2549:0):                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2550:0):                                 $similar .= '<h3><span class="LC_warning">'.
                   2551:0):                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2552:0):                                                 $osim,
                   2553:0):                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2554:0):                                             '</span></h3>';
                   2555:0):                             } elsif ($ocrsid ne '') {
                   2556:0):                                 my %old_course_desc;
                   2557:0):                                 if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2558:0):                                     %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
          5(raebur 2559:9):                                 } else {
          1(raebur 2560:0):                                     my $args;
                   2561:0):                                     if ($ocrsid ne $env{'request.course.id'}) {
                   2562:0):                                         $args = {'one_time' => 1};
                   2563:0):                                     }
                   2564:0):                                     %old_course_desc =
                   2565:0):                                         &Apache::lonnet::coursedescription($ocrsid,$args);
                   2566:0):                                     $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
          5(raebur 2567:9):                                 }
          1(raebur 2568:0):                                 $similar .=
                   2569:0):                                     '<h3><span class="LC_warning">'.
                   2570:0): 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2571:0): 				        $osim,
                   2572:0): 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2573:0): 				        $old_course_desc{'description'},
                   2574:0): 				        $old_course_desc{'num'},
                   2575:0): 				        $old_course_desc{'domain'}).
                   2576:0): 				    '</span></h3>';
1.596     raeburn  2577:                             } else {
1.596.2.12.2.  1(raebur 2578:0):                                 $similar .=
                   2579:0):                                     '<h3><span class="LC_warning">'.
                   2580:0):                                     &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2581:0):                                         $osim,
                   2582:0):                                         &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2583:0):                                     '</span></h3>';
1.596     raeburn  2584:                             }
1.596.2.12.2.  1(raebur 2585:0):                             $similar .= '<blockquote><i>'.
                   2586:0):                                         &keywords_highlight($oessay).
                   2587:0):                                         '</i></blockquote><hr />';
                   2588:0): 		        }
                   2589:0):                     }
                   2590:0):                 }
                   2591:0): 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2592:0):                                      undef,$type,$trial,$rndseed);
                   2593:0):                 if (($env{'form.lastSub'} eq 'lastonly') ||
                   2594:0):                     ($env{'form.lastSub'} eq 'datesub')  ||
                   2595:0):                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
                   2596:0): 		    my $display_part=&get_display_part($partid,$symb);
                   2597:0):                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2598:0):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2599:0):                         ' <span class="LC_internal_info">'.
                   2600:0):                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2601:0):                         '</span>&nbsp; &nbsp;';
                   2602:0): 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2603:0): 		    if (@$files) {
1.596.2.2  raeburn  2604:                         if ($hide eq 'anon') {
1.596.2.12.2.  1(raebur 2605:0):                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
1.596     raeburn  2606:                         } else {
1.596.2.12.2.  1(raebur 2607:0):                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2608:0):                                          .'<br /><span class="LC_warning">';
                   2609:0):                             if(@$files == 1) {
                   2610:0):                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2611:0):                             } else {
                   2612:0):                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
          0(raebur 2613:4):                             }
          1(raebur 2614:0):                             $lastsubonly .= '</span>';
                   2615:0):                             foreach my $file (@$files) {
                   2616:0):                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2617:0):                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
          0(raebur 2618:4):                             }
1.596     raeburn  2619:                         }
1.596.2.12.2.  1(raebur 2620:0): 			$lastsubonly.='<br />';
1.41      ng       2621: 		    }
1.596.2.12.2.  1(raebur 2622:0):                     if ($hide eq 'anon') {
                   2623:0):                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2624:0):                     } else {
                   2625:0):                         $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2626:0):                         if ($draft) {
                   2627:0):                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2628:0):                         }
                   2629:0):                         $subval =
                   2630:0): 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2631:0): 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
                   2632:0):                         if ($responsetype eq 'essay') {
                   2633:0):                             $subval =~ s{\n}{<br />}g;
                   2634:0):                         }
                   2635:0):                         $lastsubonly.=$subval."\n";
                   2636:0):                     }
                   2637:0):                     if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2638:0): 		    $lastsubonly.='</div>';
1.41      ng       2639: 		}
                   2640: 	    }
1.151     albertel 2641: 	}
1.596.2.12.2.  1(raebur 2642:0): 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2643:0):     }
                   2644:0):     $request->print($lastsubonly);
                   2645:0):     if ($env{'form.lastSub'} eq 'datesub') {
                   2646:0):         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2647: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2648:3):     }
                   2649:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2650:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2651: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2652: 								 $env{'request.course.id'},
1.44      ng       2653: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2654:5): 								 'Apache::grades::keywords_highlight',
                   2655:5):                                                                  $usec,$identifier));
1.41      ng       2656:     }
1.121     ng       2657:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2658: 	.$udom.'" />'."\n");
1.44      ng       2659:     # return if view submission with no grading option
1.596.2.12.2.  1(raebur 2660:0):     if (!&canmodify($usec)) {
                   2661:0):         $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
                   2662:0):         return;
1.180     albertel 2663:     } else {
1.468     albertel 2664: 	$request->print('</div>'."\n");
1.41      ng       2665:     }
1.33      ng       2666: 
1.596.2.12.2.  1(raebur 2667:0):     # grading message center
                   2668:0): 
                   2669:0):     if ($env{'form.compmsg'}) {
                   2670:0):         my $result='<div class="LC_Box">'.
                   2671:0):                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
                   2672:0):                    '<div class="LC_grade_message_center_body">';
                   2673:0):         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
                   2674:0):         my $msgfor = $givenn.' '.$lastname;
                   2675:0):         if (scalar(@$col_fullnames) > 0) {
                   2676:0):             my $lastone = pop(@$col_fullnames);
                   2677:0):             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
                   2678:0):         }
                   2679:0):         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
                   2680:0):         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2681:0):                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
                   2682:0): 	         '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
                   2683:0):                  ',\''.$msgfor.'\');" target="_self">'.
                   2684:0):                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
                   2685:0):                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
                   2686:0):                  ' <img src="'.$request->dir_config('lonIconsURL').
                   2687:0):                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
                   2688:0):                  '<br />&nbsp;('.
                   2689:0):                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
                   2690:0): 	         '</div></div>';
                   2691:0):         $request->print($result);
1.118     ng       2692:     }
1.41      ng       2693: 
                   2694:     my %seen = ();
                   2695:     my @partlist;
1.129     ng       2696:     my @gradePartRespid;
1.375     albertel 2697:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2698:     $request->print(
1.588     bisitz   2699:         '<div class="LC_Box">'
                   2700:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2701:     );
1.592     bisitz   2702:     $request->print(&gradeBox_start());
1.375     albertel 2703:     foreach my $part_response_id (@part_response_id) {
                   2704:     	my ($partid,$respid) = @{ $part_response_id };
                   2705: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2706: 	next if ($seen{$partid} > 0);
1.41      ng       2707: 	$seen{$partid}++;
1.524     raeburn  2708: 	push(@partlist,$partid);
                   2709: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2710: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2711:     }
1.585     bisitz   2712:     $request->print(&gradeBox_end()); # </div>
                   2713:     $request->print('</div>');
1.468     albertel 2714: 
                   2715:     $request->print('<div class="LC_grade_info_links">');
                   2716:     $request->print('</div>');
                   2717: 
1.45      ng       2718:     $result='<input type="hidden" name="partlist'.$counter.
                   2719: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2720:     $result.='<input type="hidden" name="gradePartRespid'.
                   2721: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2722:     my $ctr = 0;
                   2723:     while ($ctr < scalar(@partlist)) {
                   2724: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2725: 	    $partlist[$ctr].'" />'."\n";
                   2726: 	$ctr++;
                   2727:     }
1.468     albertel 2728:     $request->print($result.''."\n");
1.41      ng       2729: 
1.441     www      2730: # Done with printing info for one student
                   2731: 
1.468     albertel 2732:     $request->print('</div>');#LC_grade_show_user
1.441     www      2733: 
                   2734: 
1.41      ng       2735:     # print end of form
                   2736:     if ($counter == $total) {
1.592     bisitz   2737:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2738: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2739: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2740: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2741: 	my $ntstu ='<select name="NTSTU">'.
                   2742: 	    '<option>1</option><option>2</option>'.
                   2743: 	    '<option>3</option><option>5</option>'.
                   2744: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2745: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2746: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2747:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2748: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2749: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2750: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2751: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2752:         $endform.='<span class="LC_warning">'.
                   2753:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2754:                   '</span>'."\n" ;
1.349     albertel 2755:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2756:             "' name='increment' />";
1.485     albertel 2757: 	$endform.='</td></tr></table></form>';
1.41      ng       2758: 	$request->print($endform);
                   2759:     }
                   2760:     return '';
1.38      ng       2761: }
                   2762: 
1.464     albertel 2763: sub check_collaborators {
                   2764:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2765:     my ($result,@col_fullnames);
                   2766:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2767:     foreach my $part (keys(%$handgrade)) {
                   2768: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2769: 					'.maxcollaborators',
                   2770: 					$symb,$udom,$uname);
                   2771: 	next if ($ncol <= 0);
                   2772: 	$part =~ s/\_/\./g;
                   2773: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2774: 	my (@good_collaborators, @bad_collaborators);
                   2775: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2776: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2777: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2778: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2779: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2780: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2781: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2782: 	    # Doing this grep allows 'fuzzy' specification
                   2783: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2784: 			       keys(%$classlist));
                   2785: 	    if (! scalar(@matches)) {
                   2786: 		push(@bad_collaborators, $possible_collaborator);
                   2787: 	    } else {
                   2788: 		push(@good_collaborators, @matches);
                   2789: 	    }
                   2790: 	}
                   2791: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2792: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2793: 	    foreach my $name (@good_collaborators) {
                   2794: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2795: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2796: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2797: 	    }
1.596.2.4  raeburn  2798: 	    $result.='</ol><br />'."\n";
1.466     albertel 2799: 	    my ($part)=split(/\./,$part);
1.464     albertel 2800: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2801: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2802: 		"\n";
                   2803: 	}
                   2804: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2805: 	    $result.='<div class="LC_warning">';
1.464     albertel 2806: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2807: 	    $result .= '</div>';
                   2808: 	}         
                   2809: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2810: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2811: 	    $result .= &mt('This student has submitted too many '.
                   2812: 		'collaborators.  Maximum is [_1].',$ncol);
                   2813: 	    $result .= '</div>';
                   2814: 	}
                   2815:     }
                   2816:     return ($result,$fullname,\@col_fullnames);
                   2817: }
                   2818: 
1.44      ng       2819: #--- Retrieve the last submission for all the parts
1.38      ng       2820: sub get_last_submission {
1.119     ng       2821:     my ($returnhash)=@_;
1.596     raeburn  2822:     my (@string,$timestamp,%lasthidden);
1.119     ng       2823:     if ($$returnhash{'version'}) {
1.46      ng       2824: 	my %lasthash=();
                   2825: 	my ($version);
1.119     ng       2826: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2827: 	    foreach my $key (sort(split(/\:/,
                   2828: 					$$returnhash{$version.':keys'}))) {
                   2829: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2830: 		$timestamp = 
1.545     raeburn  2831: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2832: 	    }
                   2833: 	}
1.596.2.2  raeburn  2834:         my (%typeparts,%randombytry);
1.596     raeburn  2835:         my $showsurv = 
                   2836:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2837:         foreach my $key (sort(keys(%lasthash))) {
                   2838:             if ($key =~ /\.type$/) {
                   2839:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2840:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2841:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2842:                     my ($ign,@parts) = split(/\./,$key);
                   2843:                     pop(@parts);
1.596.2.3  raeburn  2844:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2845:                     if ($lasthash{$key} eq 'randomizetry') {
                   2846:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2847:                     } else {
                   2848:                         unless ($showsurv) {
                   2849:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2850:                         }
1.596     raeburn  2851:                     }
                   2852:                     delete($lasthash{$key});
                   2853:                 }
                   2854:             }
                   2855:         }
                   2856:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2857:         my @randomize = keys(%randombytry);
1.397     albertel 2858: 	foreach my $key (keys(%lasthash)) {
                   2859: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2860:             my $hide;
                   2861:             if (@hidden) {
                   2862:                 foreach my $id (@hidden) {
                   2863:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2864:                         $hide = 'anon';
1.596     raeburn  2865:                         last;
                   2866:                     }
                   2867:                 }
                   2868:             }
1.596.2.2  raeburn  2869:             unless ($hide) {
                   2870:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2871:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2872:                         if ($key =~ /^\Q$id\E/) {
                   2873:                             $hide = 'rand';
                   2874:                             last;
                   2875:                         }
                   2876:                     }
                   2877:                 }
                   2878:             }
1.397     albertel 2879: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  1(raebur 2880:0): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
          0(raebur 2881:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2882:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2883:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2884: 	}
                   2885:     }
1.397     albertel 2886:     if (!@string) {
                   2887: 	$string[0] =
1.539     riegler  2888: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2889:     }
                   2890:     return (\@string,\$timestamp);
1.38      ng       2891: }
1.35      ng       2892: 
1.44      ng       2893: #--- High light keywords, with style choosen by user.
1.38      ng       2894: sub keywords_highlight {
1.44      ng       2895:     my $string    = shift;
1.257     albertel 2896:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2897:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2898:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2899:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2900:     foreach my $keyword (@keylist) {
                   2901: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2902:     }
                   2903:     return $string;
1.38      ng       2904: }
1.36      ng       2905: 
1.596.2.12.2.  (raeburn 2906:): # For Tasks provide a mechanism to display previous version for one specific student
                   2907:): 
                   2908:): sub show_previous_task_version {
                   2909:):     my ($request,$symb) = @_;
                   2910:):     if ($symb eq '') {
          8(raebur 2911:4):         $request->print(
                   2912:4):             '<span class="LC_error">'.
                   2913:4):             &mt('Unable to handle ambiguous references.').
                   2914:4):             '</span>');
          (raeburn 2915:):         return '';
                   2916:):     }
                   2917:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2918:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2919:):     if (!&canview($usec)) {
          8(raebur 2920:4):         $request->print('<span class="LC_warning">'.
                   2921:4):                         &mt('Unable to view previous version for requested student.').
                   2922:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2923:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2924:4):                         '</span>');
          (raeburn 2925:):         return;
                   2926:):     }
                   2927:):     my $mode = 'both';
                   2928:):     my $isTask = ($symb =~/\.task$/);
                   2929:):     if ($isTask) {
                   2930:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2931:):             if ($env{'form.fullname'} eq '') {
                   2932:):                 $env{'form.fullname'} =
                   2933:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2934:):             }
                   2935:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2936:):             $request->print("\n\n".
                   2937:):                             '<div class="LC_grade_show_user">'.
                   2938:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2939:):                             '</h2>'."\n");
                   2940:):             &Apache::lonxml::clear_problem_counter();
                   2941:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2942:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2943:):             $request->print("\n</div>");
                   2944:):         }
                   2945:):     }
                   2946:):     return;
                   2947:): }
                   2948:): 
                   2949:): sub choose_task_version_form {
                   2950:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2951:):     my $isTask = ($symb =~/\.task$/);
                   2952:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2953:):     if ($isTask) {
                   2954:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2955:):                                               $udom,$uname);
                   2956:):         if (($record{'resource.0.version'} eq '') ||
                   2957:):             ($record{'resource.0.version'} < 2)) {
                   2958:):             return ($record{'resource.0.version'},
                   2959:):                     $record{'resource.0.version'},$result,$js);
                   2960:):         } else {
                   2961:):             $current = $record{'resource.0.version'};
                   2962:):         }
                   2963:):         if ($env{'form.previousversion'}) {
                   2964:):             $displayed = $env{'form.previousversion'};
                   2965:):             $rowtitle = &mt('Choose another version:')
                   2966:):         } else {
                   2967:):             $displayed = $current;
                   2968:):             $rowtitle = &mt('Show earlier version:');
                   2969:):         }
                   2970:):         $result = '<div class="LC_left_float">';
                   2971:):         my $list;
                   2972:):         my $numversions = 0;
                   2973:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2974:):             if ($i == $current) {
                   2975:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2976:):                     next;
                   2977:):                 } else {
                   2978:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2979:):                     $numversions ++;
                   2980:):                 }
                   2981:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2982:):                 unless ($i == $env{'form.previousversion'}) {
                   2983:):                     $numversions ++;
                   2984:):                 }
                   2985:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2986:):             }
                   2987:):         }
                   2988:):         if ($numversions) {
                   2989:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2990:):             $result .=
                   2991:):                 '<form name="getprev" method="post" action=""'.
                   2992:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2993:):                 &Apache::loncommon::start_data_table().
                   2994:):                 &Apache::loncommon::start_data_table_row().
                   2995:):                 '<th align="left">'.$rowtitle.'</th>'.
                   2996:):                 '<td><select name="version">'.
                   2997:):                 '<option>'.&mt('Select').'</option>'.
                   2998:):                 $list.
                   2999:):                 '</select></td>'.
                   3000:):                 &Apache::loncommon::end_data_table_row();
                   3001:):             unless ($nomenu) {
                   3002:):                 $result .= &Apache::loncommon::start_data_table_row().
                   3003:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3004:):                 '<td><span class="LC_nobreak">'.
                   3005:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3006:):                 &mt('Yes').'</label>'.
                   3007:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3008:):                 '</span></td>'.
                   3009:):                 &Apache::loncommon::end_data_table_row();
                   3010:):             }
                   3011:):             $result .=
                   3012:):                 &Apache::loncommon::start_data_table_row().
                   3013:):                 '<th align="left">&nbsp;</th>'.
                   3014:):                 '<td>'.
                   3015:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3016:):                 '</td>'.
                   3017:):                 &Apache::loncommon::end_data_table_row().
                   3018:):                 &Apache::loncommon::end_data_table().
                   3019:):                 '</form>';
                   3020:):             $js = &previous_display_javascript($nomenu,$current);
                   3021:):         } elsif ($displayed && $nomenu) {
                   3022:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3023:):         } else {
                   3024:):             $result .= &mt('No previous versions to show for this student');
                   3025:):         }
                   3026:):         $result .= '</div>';
                   3027:):     }
                   3028:):     return ($current,$displayed,$result,$js);
                   3029:): }
                   3030:): 
                   3031:): sub previous_display_javascript {
                   3032:):     my ($nomenu,$current) = @_;
                   3033:):     my $js = <<"JSONE";
                   3034:): <script type="text/javascript">
                   3035:): // <![CDATA[
                   3036:): function previousVersion(uname,udom,symb) {
                   3037:):     var current = '$current';
                   3038:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3039:):     var prevstr = new RegExp("^\\\\d+\$");
                   3040:):     if (!prevstr.test(version)) {
                   3041:):         return false;
                   3042:):     }
                   3043:):     var url = '';
                   3044:):     if (version == current) {
                   3045:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3046:):     } else {
                   3047:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3048:):     }
                   3049:): JSONE
                   3050:):     if ($nomenu) {
                   3051:):         $js .= <<"JSTWO";
                   3052:):     document.location.href = url;
                   3053:): JSTWO
                   3054:):     } else {
                   3055:):         $js .= <<"JSTHREE";
                   3056:):     var newwin = 0;
                   3057:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3058:):         if (document.getprev.prevwin[i].checked == true) {
                   3059:):             newwin = document.getprev.prevwin[i].value;
                   3060:):         }
                   3061:):     }
                   3062:):     if (newwin == 1) {
                   3063:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3064:):         url = url+'&inhibitmenu=yes';
                   3065:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3066:):             previousWin = window.open(url,'',options,1);
                   3067:):         } else {
                   3068:):             previousWin.location.href = url;
                   3069:):         }
                   3070:):         previousWin.focus();
                   3071:):         return false;
                   3072:):     } else {
                   3073:):         document.location.href = url;
                   3074:):         return false;
                   3075:):     }
                   3076:): JSTHREE
                   3077:):     }
                   3078:):     $js .= <<"ENDJS";
                   3079:):     return false;
                   3080:): }
                   3081:): // ]]>
                   3082:): </script>
                   3083:): ENDJS
                   3084:): 
                   3085:): }
                   3086:): 
1.44      ng       3087: #--- Called from submission routine
1.38      ng       3088: sub processHandGrade {
1.596.2.12.2.  1(raebur 3089:0):     my ($request,$symb) = @_;
1.324     albertel 3090:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3091:     my $button = $env{'form.gradeOpt'};
                   3092:     my $ngrade = $env{'form.NCT'};
                   3093:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3094:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3095:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3096: 
1.44      ng       3097:     if ($button eq 'Save & Next') {
                   3098: 	my $ctr = 0;
                   3099: 	while ($ctr < $ngrade) {
1.257     albertel 3100: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 3101:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3102:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3103: 	    if ($errorflag eq 'no_score') {
                   3104: 		$ctr++;
                   3105: 		next;
                   3106: 	    }
1.104     albertel 3107: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 3108:4):                 $request->print(
                   3109:4):                     '<span class="LC_error">'
                   3110:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3111:4):                    .'</span>');
1.104     albertel 3112: 		$ctr++;
                   3113: 		next;
                   3114: 	    }
1.596.2.12.2.  1(raebur 3115:5):             if ($numhidden) {
                   3116:5):                 $request->print(
                   3117:5):                     '<span class="LC_info">'
                   3118:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3119:5):                    .'</span><br />');
                   3120:5):             }
1.257     albertel 3121: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3122: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3123: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3124:             my ($feedurl,$showsymb) =
                   3125: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3126: 	    my $messagetail;
1.62      albertel 3127: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3128: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3129: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3130: 		$subject.=' ['.$restitle.']';
1.44      ng       3131: 		my (@msgnum) = split(/,/,$includemsg);
                   3132: 		foreach (@msgnum) {
1.257     albertel 3133: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3134: 		}
1.80      ng       3135: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3136: 		if ($env{'form.withgrades'.$ctr}) {
                   3137: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3138: 		    $messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3139:0): 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3140: 		}
                   3141: 		$msgstatus = 
                   3142:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3143: 						     $message.$messagetail,
1.418     albertel 3144:                                                      undef,$feedurl,undef,
1.386     raeburn  3145:                                                      undef,undef,$showsymb,
                   3146:                                                      $restitle);
1.574     bisitz   3147: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  3148: 				$msgstatus.'<br />');
1.44      ng       3149: 	    }
1.257     albertel 3150: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3151: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3152: 		foreach my $collabstr (@collabstrs) {
                   3153: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3154: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3155: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3156: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3157: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3158: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3159: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3160: 			    next;
1.418     albertel 3161: 			} elsif ($message ne '') {
                   3162: 			    my ($baseurl,$showsymb) = 
                   3163: 				&get_feedurl_and_symb($symb,$collaborator,
                   3164: 						      $udom);
                   3165: 			    if ($env{'form.withgrades'.$ctr}) {
                   3166: 				$messagetail = " for <a href=\"".
1.596.2.12.2.  1(raebur 3167:0):                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3168: 			    }
1.418     albertel 3169: 			    $msgstatus = 
                   3170: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3171: 			}
1.44      ng       3172: 		    }
                   3173: 		}
                   3174: 	    }
                   3175: 	    $ctr++;
                   3176: 	}
                   3177:     }
                   3178: 
1.596.2.12.2.  1(raebur 3179:0):     my $res_error;
                   3180:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
                   3181:0):     if ($res_error) {
                   3182:0):         $request->print(&navmap_errormsg());
                   3183:0):         return;
                   3184:0):     }
                   3185:0): 
                   3186:0):     my %keyhash = ();
                   3187:0):     if ($numessay) {
1.119     ng       3188: 	# Keywords sorted in alphabatical order
1.257     albertel 3189: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3190: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3191: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3192: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3193: 	$env{'form.keywords'} = join(' ',@keywords);
                   3194: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3195: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3196: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3197: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3198: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.596.2.12.2.  1(raebur 3199:0):     }
1.119     ng       3200: 
1.596.2.12.2.  1(raebur 3201:0):     if ($env{'form.compmsg'}) {
1.119     ng       3202: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3203: 	# New messages are saved in env for the next student.
1.119     ng       3204: 	# All messages are saved in nohist_handgrade.db
                   3205: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3206: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3207: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3208: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3209: 		$idx++;
                   3210: 	    }
                   3211: 	    $ctr++;
1.41      ng       3212: 	}
1.119     ng       3213: 	$ctr = 0;
                   3214: 	while ($ctr < $ngrade) {
1.257     albertel 3215: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3216: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3217: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3218: 		$idx++;
                   3219: 	    }
                   3220: 	    $ctr++;
1.41      ng       3221: 	}
1.257     albertel 3222: 	$env{'form.savemsgN'} = --$idx;
                   3223: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.596.2.12.2.  1(raebur 3224:0):     }
                   3225:0):     if (($numessay) || ($env{'form.compmsg'})) {
1.119     ng       3226: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3227: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3228:     }
1.596.2.12.2.  1(raebur 3229:0): 
1.44      ng       3230:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3231:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3232:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3233: 	my ($ctr,$total) = (0,0);
                   3234: 	while ($ctr < $ngrade) {
1.257     albertel 3235: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3236: 	    $ctr++;
                   3237: 	}
1.257     albertel 3238: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3239: 	$ctr = 0;
                   3240: 	while ($ctr < $total) {
1.257     albertel 3241: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3242: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3243: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.596.2.12.2.  1(raebur 3244:0): 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3245: 	    $ctr++;
                   3246: 	}
                   3247: 	return '';
                   3248:     }
1.36      ng       3249: 
1.44      ng       3250:     # Get the next/previous one or group of students
1.257     albertel 3251:     my $firststu = $env{'form.unamedom0'};
                   3252:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3253:     my $ctr = 2;
1.41      ng       3254:     while ($laststu eq '') {
1.257     albertel 3255: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3256: 	$ctr++;
                   3257: 	$laststu = $firststu if ($ctr > $ngrade);
                   3258:     }
1.44      ng       3259: 
1.41      ng       3260:     my (@parsedlist,@nextlist);
                   3261:     my ($nextflg) = 0;
1.524     raeburn  3262:     foreach my $item (sort 
1.294     albertel 3263: 	     {
                   3264: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3265: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3266: 		 }
                   3267: 		 return $a cmp $b;
                   3268: 	     } (keys(%$fullname))) {
1.41      ng       3269: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3270: 	    push(@parsedlist,$item);
1.41      ng       3271: 	}
1.524     raeburn  3272: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3273: 	if ($button eq 'Previous') {
1.524     raeburn  3274: 	    last if ($item eq $firststu);
                   3275: 	    push(@parsedlist,$item);
1.41      ng       3276: 	}
                   3277:     }
                   3278:     $ctr = 0;
                   3279:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3280:     foreach my $student (@parsedlist) {
1.257     albertel 3281: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3282: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3283: 	
                   3284: 	if ($submitonly eq 'queued') {
                   3285: 	    my %queue_status = 
                   3286: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3287: 							$udom,$uname);
                   3288: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3289: 	}
                   3290: 
1.156     albertel 3291: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3292: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3293: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3294: 	    my $submitted = 0;
1.248     albertel 3295: 	    my $ungraded = 0;
                   3296: 	    my $incorrect = 0;
1.524     raeburn  3297: 	    foreach my $item (keys(%status)) {
                   3298: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3299: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3300: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3301: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3302: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3303: 		    $submitted = 0;
                   3304: 		}
1.41      ng       3305: 	    }
1.156     albertel 3306: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3307: 				     $submitonly eq 'incorrect' ||
                   3308: 				     $submitonly eq 'graded'));
1.248     albertel 3309: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3310: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3311: 	}
1.524     raeburn  3312: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3313: 	last if ($ctr == $ntstu);
1.41      ng       3314: 	$ctr++;
                   3315:     }
1.36      ng       3316: 
1.41      ng       3317:     $ctr = 0;
                   3318:     my $total = scalar(@nextlist)-1;
1.39      ng       3319: 
1.524     raeburn  3320:     foreach (sort(@nextlist)) {
1.41      ng       3321: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3322: 	$env{'form.student'}  = $uname;
                   3323: 	$env{'form.userdom'}  = $udom;
                   3324: 	$env{'form.fullname'} = $$fullname{$_};
1.596.2.12.2.  1(raebur 3325:0): 	&submission($request,$ctr,$total,$symb);
1.41      ng       3326: 	$ctr++;
                   3327:     }
                   3328:     if ($total < 0) {
1.596.2.12.2.  1(raebur 3329:0):         my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3330: 	$request->print($the_end);
                   3331:     }
                   3332:     return '';
1.38      ng       3333: }
1.36      ng       3334: 
1.44      ng       3335: #---- Save the score and award for each student, if changed
1.38      ng       3336: sub saveHandGrade {
1.324     albertel 3337:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3338:     my @version_parts;
1.104     albertel 3339:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3340: 					   $env{'request.course.id'});
1.104     albertel 3341:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3342:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3343:     my @parts_graded;
1.77      ng       3344:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3345:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3346:     my %aggregate = ();
                   3347:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3348:5):     if ($env{'form.HIDE'.$newflg}) {
                   3349:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3350:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3351:5):         $totchg += $numchgs;
                   3352:5):     }
1.301     albertel 3353:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3354:     foreach my $new_part (@parts) {
1.337     banghart 3355: 	#collaborator ($submi may vary for different parts
1.259     banghart 3356: 	if ($submitter && $new_part ne $part) { next; }
                   3357: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3358: 	if ($dropMenu eq 'excused') {
1.259     banghart 3359: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3360: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3361: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3362: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3363: 		}
1.364     banghart 3364: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3365: 	    }
1.125     ng       3366: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3367: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3368: 	    foreach my $key (keys(%record)) {
1.259     banghart 3369: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3370: 	    }
1.259     banghart 3371: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3372: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3373:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3374: 
                   3375:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3376: 					       [$new_part]);
                   3377:             my $aggtries =$totaltries;
1.269     raeburn  3378:             if ($last_resets{$new_part}) {
1.270     albertel 3379:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3380: 					   $new_part);
1.269     raeburn  3381:             }
1.270     albertel 3382: 
                   3383:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3384:             if ($aggtries > 0) {
1.327     albertel 3385:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3386:                 $aggregateflag = 1;
                   3387:             }
1.125     ng       3388: 	} elsif ($dropMenu eq '') {
1.259     banghart 3389: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3390: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3391: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3392: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3393: 		next;
                   3394: 	    }
1.259     banghart 3395: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3396: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3397: 	    my $partial= $pts/$wgt;
1.259     banghart 3398: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3399: 		#do not update score for part if not changed.
1.346     banghart 3400:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3401: 		next;
1.251     banghart 3402: 	    } else {
1.524     raeburn  3403: 	        push(@parts_graded,$new_part);
1.153     albertel 3404: 	    }
1.259     banghart 3405: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3406: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3407: 	    }
1.259     banghart 3408: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3409: 	    if ($partial == 0) {
1.153     albertel 3410: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3411: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3412: 		}
1.41      ng       3413: 	    } else {
1.153     albertel 3414: 		if ($record{$reckey} ne 'correct_by_override') {
                   3415: 		    $newrecord{$reckey} = 'correct_by_override';
                   3416: 		}
                   3417: 	    }	    
                   3418: 	    if ($submitter && 
1.259     banghart 3419: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3420: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3421: 	    }
1.259     banghart 3422: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3423: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3424: 	}
1.259     banghart 3425: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3426: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3427: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3428: 	        $dropMenu eq 'reset status')
                   3429: 	   {
1.524     raeburn  3430: 	    push(@version_parts,$new_part);
1.259     banghart 3431: 	}
1.41      ng       3432:     }
1.301     albertel 3433:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3434:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3435: 
1.344     albertel 3436:     if (%newrecord) {
                   3437:         if (@version_parts) {
1.364     banghart 3438:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3439:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3440: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3441: 	    foreach my $new_part (@version_parts) {
                   3442: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3443: 				$new_part,\%newrecord);
                   3444: 	    }
1.259     banghart 3445:         }
1.44      ng       3446: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3447: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3448: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3449: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3450:     }
1.269     raeburn  3451:     if ($aggregateflag) {
                   3452:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3453: 			      $cdom,$cnum);
1.269     raeburn  3454:     }
1.596.2.12.2.  1(raebur 3455:5):     return ('',$pts,$wgt,$totchg);
                   3456:5): }
                   3457:5): 
                   3458:5): sub makehidden {
                   3459:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3460:5):     return unless (ref($record) eq 'HASH');
                   3461:5):     my %modified;
                   3462:5):     my $numchanged = 0;
                   3463:5):     if (exists($record->{$version.':keys'})) {
                   3464:5):         my $partsregexp = $parts;
                   3465:5):         $partsregexp =~ s/,/|/g;
                   3466:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3467:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3468:5):                  my $item = $1;
                   3469:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3470:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3471:5):                  }
                   3472:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3473:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3474:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3475:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3476:5):             }
                   3477:5):         }
                   3478:5):         if (keys(%modified)) {
                   3479:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3480:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3481:5):                 $numchanged ++;
                   3482:5):             }
                   3483:5):         }
                   3484:5):     }
                   3485:5):     return $numchanged;
1.36      ng       3486: }
1.322     albertel 3487: 
1.380     albertel 3488: sub check_and_remove_from_queue {
                   3489:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3490:     my @ungraded_parts;
                   3491:     foreach my $part (@{$parts}) {
                   3492: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3493: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3494: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3495: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3496: 		) {
                   3497: 	    push(@ungraded_parts, $part);
                   3498: 	}
                   3499:     }
                   3500:     if ( !@ungraded_parts ) {
                   3501: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3502: 					       $cnum,$domain,$stuname);
                   3503:     }
                   3504: }
                   3505: 
1.337     banghart 3506: sub handback_files {
                   3507:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3508:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3509:     my $res_error;
                   3510:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3511:     if ($res_error) {
                   3512:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3513:         return;
                   3514:     }
1.596.2.4  raeburn  3515:     my @handedback;
                   3516:     my $file_msg;
1.375     albertel 3517:     my @part_response_id = &flatten_responseType($responseType);
                   3518:     foreach my $part_response_id (@part_response_id) {
                   3519:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3520: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3521:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3522:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3523:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3524: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3525:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3526:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3527:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3528:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3529: 		        &file_name_version_ext($answer_file);
1.355     banghart 3530: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3531:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3532:):                     my ($dir_list,$listerror) =
                   3533:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3534:):                                                  $domain,$stuname,$getpropath);
                   3535:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3536:3):                     # fix filename
1.355     banghart 3537:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3538:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3539:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3540:             	                                $save_file_name);
1.337     banghart 3541:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3542:                         $request->print('<br /><span class="LC_error">'.
                   3543:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3544:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3545:                                         '</span>');
1.356     banghart 3546:                     } else {
1.360     banghart 3547:                         # mark the file as read only
1.596.2.4  raeburn  3548:                         push(@handedback,$save_file_name);
1.367     albertel 3549: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3550: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3551: 			}
                   3552:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3553: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3554: 
1.337     banghart 3555:                     }
1.596.2.12.2.  3(raebur 3556: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 3557:                 }
                   3558:             }
                   3559:         }
1.596.2.4  raeburn  3560:     }
                   3561:     if (@handedback > 0) {
                   3562:         $request->print('<br />');
                   3563:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3564:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3565:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3566:         my ($subject,$message);
                   3567:         if (scalar(@handedback) == 1) {
                   3568:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
1.596.2.12.2.  1(raebur 3569:0):             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
1.596.2.4  raeburn  3570:         } else {
                   3571:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3572:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3573:         }
                   3574:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3575:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3576:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3577:         my ($feedurl,$showsymb) =
                   3578:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3579:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3580:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3581:         my $msgstatus =
                   3582:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3583:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3584:                  $restitle);
                   3585:         if ($msgstatus) {
                   3586:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3587:         }
                   3588:     }
1.338     banghart 3589:     return;
1.337     banghart 3590: }
                   3591: 
1.418     albertel 3592: sub get_feedurl_and_symb {
                   3593:     my ($symb,$uname,$udom) = @_;
                   3594:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3595:     $url = &Apache::lonnet::clutter($url);
                   3596:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3597: 					$symb,$udom,$uname);
                   3598:     if ($encrypturl =~ /^yes$/i) {
                   3599: 	&Apache::lonenc::encrypted(\$url,1);
                   3600: 	&Apache::lonenc::encrypted(\$symb,1);
                   3601:     }
                   3602:     return ($url,$symb);
                   3603: }
                   3604: 
1.313     banghart 3605: sub get_submitted_files {
                   3606:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3607:     my @files;
                   3608:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3609:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3610:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3611:     	    push(@files,$file_url.$file);
                   3612:         }
                   3613:     }
                   3614:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3615:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3616:     }
                   3617:     return (\@files);
                   3618: }
1.322     albertel 3619: 
1.269     raeburn  3620: # ----------- Provides number of tries since last reset.
                   3621: sub get_num_tries {
                   3622:     my ($record,$last_reset,$part) = @_;
                   3623:     my $timestamp = '';
                   3624:     my $num_tries = 0;
                   3625:     if ($$record{'version'}) {
                   3626:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3627:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3628:                 $timestamp = $$record{$version.':timestamp'};
                   3629:                 if ($timestamp > $last_reset) {
                   3630:                     $num_tries ++;
                   3631:                 } else {
                   3632:                     last;
                   3633:                 }
                   3634:             }
                   3635:         }
                   3636:     }
                   3637:     return $num_tries;
                   3638: }
                   3639: 
                   3640: # ----------- Determine decrements required in aggregate totals 
                   3641: sub decrement_aggs {
                   3642:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3643:     my %decrement = (
                   3644:                         attempts => 0,
                   3645:                         users => 0,
                   3646:                         correct => 0
                   3647:                     );
                   3648:     $decrement{'attempts'} = $aggtries;
                   3649:     if ($solvedstatus =~ /^correct/) {
                   3650:         $decrement{'correct'} = 1;
                   3651:     }
                   3652:     if ($aggtries == $totaltries) {
                   3653:         $decrement{'users'} = 1;
                   3654:     }
1.524     raeburn  3655:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3656:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3657:     }
                   3658:     return;
                   3659: }
                   3660: 
                   3661: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3662: sub get_last_resets {
1.270     albertel 3663:     my ($symb,$courseid,$partids) =@_;
                   3664:     my %last_resets;
1.269     raeburn  3665:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3666:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3667:     my @keys;
                   3668:     foreach my $part (@{$partids}) {
                   3669: 	push(@keys,"$symb\0$part\0resettime");
                   3670:     }
                   3671:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3672: 				     $cdom,$cname);
                   3673:     foreach my $part (@{$partids}) {
                   3674: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3675:     }
1.270     albertel 3676:     return %last_resets;
1.269     raeburn  3677: }
                   3678: 
1.251     banghart 3679: # ----------- Handles creating versions for portfolio files as answers
                   3680: sub version_portfiles {
1.343     banghart 3681:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3682:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3683:     my @returned_keys;
1.255     banghart 3684:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3685:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3686:     foreach my $key (keys(%$record)) {
1.259     banghart 3687:         my $new_portfiles;
1.263     banghart 3688:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3689:             my @versioned_portfiles;
1.367     albertel 3690:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3691:             foreach my $file (@portfiles) {
1.306     banghart 3692:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3693:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3694: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3695: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3696:):                 my $getpropath = 1;
                   3697:):                 my ($dir_list,$listerror) =
                   3698:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3699:):                                              $stu_name,$getpropath);
                   3700:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3701:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3702:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3703:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3704:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3705:                         [$directory.$new_answer],
1.306     banghart 3706:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3707:                 }
1.252     banghart 3708:             }
1.343     banghart 3709:             $$record{$key} = join(',',@versioned_portfiles);
                   3710:             push(@returned_keys,$key);
1.251     banghart 3711:         }
                   3712:     } 
1.343     banghart 3713:     return (@returned_keys);   
1.305     banghart 3714: }
                   3715: 
1.307     banghart 3716: sub get_next_version {
1.341     banghart 3717:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3718:     my $version;
1.596.2.12.2.  (raeburn 3719:):     if (ref($dir_list) eq 'ARRAY') {
                   3720:):         foreach my $row (@{$dir_list}) {
                   3721:):             my ($file) = split(/\&/,$row,2);
                   3722:):             my ($file_name,$file_version,$file_ext) =
                   3723:): 	        &file_name_version_ext($file);
                   3724:):             if (($file_name eq $answer_name) && 
                   3725:): 	        ($file_ext eq $answer_ext)) {
                   3726:):                 # gets here if filename and extension match, 
                   3727:):                 # regardless of version
1.307     banghart 3728:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3729:):                     # a versioned file is found  so save it for later
                   3730:):                     if ($file_version > $version) {
                   3731:): 		        $version = $file_version;
                   3732:):                     }
1.307     banghart 3733: 	        }
                   3734:             }
                   3735:         }
1.596.2.12.2.  (raeburn 3736:):     }
1.307     banghart 3737:     $version ++;
                   3738:     return($version);
                   3739: }
                   3740: 
1.305     banghart 3741: sub version_selected_portfile {
1.306     banghart 3742:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3743:     my ($answer_name,$answer_ver,$answer_ext) =
                   3744:         &file_name_version_ext($file_name);
                   3745:     my $new_answer;
                   3746:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3747:     if($env{'form.copy'} eq '-1') {
                   3748:         $new_answer = 'problem getting file';
                   3749:     } else {
                   3750:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3751:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3752:                             $stu_name,$domain,'copy',
                   3753: 		        '/portfolio'.$directory.$new_answer);
                   3754:     }    
                   3755:     return ($new_answer);
1.251     banghart 3756: }
                   3757: 
1.304     albertel 3758: sub file_name_version_ext {
                   3759:     my ($file)=@_;
                   3760:     my @file_parts = split(/\./, $file);
                   3761:     my ($name,$version,$ext);
                   3762:     if (@file_parts > 1) {
                   3763: 	$ext=pop(@file_parts);
                   3764: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3765: 	    $version=pop(@file_parts);
                   3766: 	}
                   3767: 	$name=join('.',@file_parts);
                   3768:     } else {
                   3769: 	$name=join('.',@file_parts);
                   3770:     }
                   3771:     return($name,$version,$ext);
                   3772: }
                   3773: 
1.44      ng       3774: #--------------------------------------------------------------------------------------
                   3775: #
                   3776: #-------------------------- Next few routines handles grading by section or whole class
                   3777: #
                   3778: #--- Javascript to handle grading by section or whole class
1.42      ng       3779: sub viewgrades_js {
                   3780:     my ($request) = shift;
                   3781: 
1.539     riegler  3782:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3783:6):     &js_escape(\$alertmsg);
          1(raebur 3784:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3785:    function writePoint(partid,weight,point) {
1.125     ng       3786: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3787: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3788: 	if (point == "textval") {
1.125     ng       3789: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3790: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3791: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3792: 		var resetbox = false;
                   3793: 		for (var i=0; i<radioButton.length; i++) {
                   3794: 		    if (radioButton[i].checked) {
                   3795: 			textbox.value = i;
                   3796: 			resetbox = true;
                   3797: 		    }
                   3798: 		}
                   3799: 		if (!resetbox) {
                   3800: 		    textbox.value = "";
                   3801: 		}
                   3802: 		return;
                   3803: 	    }
1.109     matthew  3804: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3805: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3806: 				   ") greater than the weight for the part. Accept?");
                   3807: 		if (resp == false) {
                   3808: 		    textbox.value = "";
                   3809: 		    return;
                   3810: 		}
                   3811: 	    }
1.42      ng       3812: 	    for (var i=0; i<radioButton.length; i++) {
                   3813: 		radioButton[i].checked=false;
1.109     matthew  3814: 		if (parseFloat(point) == i) {
1.42      ng       3815: 		    radioButton[i].checked=true;
                   3816: 		}
                   3817: 	    }
1.41      ng       3818: 
1.42      ng       3819: 	} else {
1.125     ng       3820: 	    textbox.value = parseFloat(point);
1.42      ng       3821: 	}
1.41      ng       3822: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3823: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3824: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3825: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3826: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3827: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3828: 	    if (saveval != "correct") {
                   3829: 		scorename.value = point;
1.43      ng       3830: 		if (selname[0].selected != true) {
                   3831: 		    selname[0].selected = true;
                   3832: 		}
1.42      ng       3833: 	    }
                   3834: 	}
1.125     ng       3835: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3836:     }
                   3837: 
                   3838:     function writeRadText(partid,weight) {
1.125     ng       3839: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3840: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3841:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3842: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3843: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3844: 	    for (var i=0; i<radioButton.length; i++) {
                   3845: 		radioButton[i].checked=false;
                   3846: 
                   3847: 	    }
                   3848: 	    textbox.value = "";
                   3849: 
                   3850: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3851: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3852: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3853: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3854: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3855: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3856: 		if ((saveval != "correct") || override) {
1.42      ng       3857: 		    scorename.value = "";
1.125     ng       3858: 		    if (selval[1].selected) {
                   3859: 			selname[1].selected = true;
                   3860: 		    } else {
                   3861: 			selname[2].selected = true;
                   3862: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3863: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3864: 		    }
1.42      ng       3865: 		}
                   3866: 	    }
1.43      ng       3867: 	} else {
                   3868: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3869: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3870: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3871: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3872: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3873: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3874: 		if ((saveval != "correct") || override) {
1.125     ng       3875: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3876: 		    selname[0].selected = true;
                   3877: 		}
                   3878: 	    }
                   3879: 	}	    
1.42      ng       3880:     }
                   3881: 
                   3882:     function changeSelect(partid,user) {
1.125     ng       3883: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3884: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3885: 	var point  = textbox.value;
1.125     ng       3886: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3887: 
1.109     matthew  3888: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3889: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3890: 	    textbox.value = "";
                   3891: 	    return;
                   3892: 	}
1.109     matthew  3893: 	if (parseFloat(point) > parseFloat(weight)) {
                   3894: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3895: 			       ") greater than the weight of the part. Accept?");
                   3896: 	    if (resp == false) {
                   3897: 		textbox.value = "";
                   3898: 		return;
                   3899: 	    }
                   3900: 	}
1.42      ng       3901: 	selval[0].selected = true;
                   3902:     }
                   3903: 
                   3904:     function changeOneScore(partid,user) {
1.125     ng       3905: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3906: 	if (selval[1].selected || selval[2].selected) {
                   3907: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3908: 	    if (selval[2].selected) {
                   3909: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3910: 	    }
1.269     raeburn  3911:         }
1.42      ng       3912:     }
                   3913: 
                   3914:     function resetEntry(numpart) {
                   3915: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3916: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3917: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3918: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3919: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3920: 	    for (var i=0; i<radioButton.length; i++) {
                   3921: 		radioButton[i].checked=false;
                   3922: 
                   3923: 	    }
                   3924: 	    textbox.value = "";
                   3925: 	    selval[0].selected = true;
                   3926: 
                   3927: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3928: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3929: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3930: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3931: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3932: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3933: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3934: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3935: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3936: 		if (saveselval == "excused") {
1.43      ng       3937: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3938: 		} else {
1.43      ng       3939: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3940: 		}
                   3941: 	    }
1.41      ng       3942: 	}
1.42      ng       3943:     }
                   3944: 
1.41      ng       3945: VIEWJAVASCRIPT
1.42      ng       3946: }
                   3947: 
1.44      ng       3948: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3949: sub viewgrades {
1.596.2.12.2.  1(raebur 3950:0):     my ($request,$symb) = @_;
1.42      ng       3951:     &viewgrades_js($request);
1.41      ng       3952: 
1.168     albertel 3953:     #need to make sure we have the correct data for later EXT calls, 
                   3954:     #thus invalidate the cache
                   3955:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3956:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3957:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3958:     &Apache::lonnet::clear_EXT_cache_status();
                   3959: 
1.398     albertel 3960:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3961: 
                   3962:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3963:     $result.=&jscriptNform($symb);
1.41      ng       3964: 
1.44      ng       3965:     #beginning of class grading form
1.442     banghart 3966:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3967:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3968: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3969: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3970: 	&build_section_inputs().
1.442     banghart 3971: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3972: 
1.596.2.12.2.  7(raebur 3973:6):     #retrieve selected groups
                   3974:6):     my (@groups,$group_display);
          8(raebur 3975:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 3976:6):     if (grep(/^all$/,@groups)) {
                   3977:6):         @groups = ('all');
                   3978:6):     } elsif (grep(/^none$/,@groups)) {
                   3979:6):         @groups = ('none');
                   3980:6):     } elsif (@groups > 0) {
                   3981:6):         $group_display = join(', ',@groups);
                   3982:6):     }
                   3983:6): 
                   3984:6):     my ($common_header,$specific_header,@sections,$section_display);
                   3985:6):     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3986:6):     if (grep(/^all$/,@sections)) {
                   3987:6):         @sections = ('all');
                   3988:6):         if ($group_display) {
                   3989:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3990:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3991:6):         } elsif (grep(/^none$/,@groups)) {
                   3992:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3993:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3994:6):         } else {
                   3995:6):             $common_header = &mt('Assign Common Grade to Class');
                   3996:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3997:6):         }
                   3998:6):     } elsif (grep(/^none$/,@sections)) {
                   3999:6):         @sections = ('none');
                   4000:6):         if ($group_display) {
                   4001:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   4002:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   4003:6):         } elsif (grep(/^none$/,@groups)) {
                   4004:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   4005:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   4006:6):         } else {
                   4007:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   4008:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   4009:6):         }
                   4010:6):     } else {
                   4011:6):         $section_display = join (", ",@sections);
                   4012:6):         if ($group_display) {
                   4013:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   4014:6):                                  $section_display,$group_display);
                   4015:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4016:6):                                    $section_display,$group_display);
                   4017:6):         } elsif (grep(/^none$/,@groups)) {
                   4018:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4019:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4020:6):         } else {
                   4021:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4022:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4023:6):         }
1.52      albertel 4024:     }
1.596.2.12.2.  7(raebur 4025:6):     my %submit_types = &substatus_options();
                   4026:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4027:6): 
                   4028:6):     if ($env{'form.submitonly'} eq 'all') {
                   4029:6):         $result.= '<h3>'.$common_header.'</h3>';
                   4030:6):     } else {
                   4031:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   4032:6):     }
                   4033:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4034:     #radio buttons/text box for assigning points for a section or class.
                   4035:     #handles different parts of a problem
1.582     raeburn  4036:     my $res_error;
                   4037:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4038:     if ($res_error) {
                   4039:         return &navmap_errormsg();
                   4040:     }
1.42      ng       4041:     my %weight = ();
                   4042:     my $ctsparts = 0;
1.45      ng       4043:     my %seen = ();
1.375     albertel 4044:     my @part_response_id = &flatten_responseType($responseType);
                   4045:     foreach my $part_response_id (@part_response_id) {
                   4046:     	my ($partid,$respid) = @{ $part_response_id };
                   4047: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4048: 	next if $seen{$partid};
                   4049: 	$seen{$partid}++;
1.42      ng       4050: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4051: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4052: 
1.324     albertel 4053: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4054: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4055: 	my $ctr = 0;
1.42      ng       4056: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4057: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4058: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4059: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4060: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4061: 	    $ctr++;
                   4062: 	}
1.485     albertel 4063: 	$radio.='</tr></table>';
                   4064: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4065: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4066: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4067: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 4068:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4069:3):                 '<select name="SELVAL_'.$partid.'" '.
                   4070:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 4071: 		$weight{$partid}.')"> '.
1.401     albertel 4072: 	    '<option selected="selected"> </option>'.
1.485     albertel 4073: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4074: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4075: 	    '</select></td>'.
                   4076:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4077: 	$line.='<input type="hidden" name="partid_'.
                   4078: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4079: 	$line.='<input type="hidden" name="weight_'.
                   4080: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4081: 
                   4082: 	$result.=
                   4083: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4084: 	    '<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 4085: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4086: 	$ctsparts++;
1.41      ng       4087:     }
1.474     albertel 4088:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4089: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4090:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4091: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4092: 
1.44      ng       4093:     #table listing all the students in a section/class
                   4094:     #header of table
1.596.2.12.2.  7(raebur 4095:6):     if ($env{'form.submitonly'} eq 'all') { 
                   4096:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   4097:6):     } else {
                   4098:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   4099:6):     }
                   4100:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4101: 	      &Apache::loncommon::start_data_table_header_row().
                   4102: 	      '<th>'.&mt('No.').'</th>'.
                   4103: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4104:     my $partserror;
                   4105:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4106:     if ($partserror) {
                   4107:         return &navmap_errormsg();
                   4108:     }
1.324     albertel 4109:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4110:     my @partids = ();
1.41      ng       4111:     foreach my $part (@parts) {
                   4112: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  4113:         my $narrowtext = &mt('Tries');
                   4114: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       4115: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 4116: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4117:         push(@partids,$partid);
1.596.2.12.2.  1(raebur 4118:0): #
                   4119:0): # FIXME: Looks like $display looks at English text
                   4120:0): #
1.324     albertel 4121: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4122: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4123: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 4124:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   4125:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4126: 	    next;
1.485     albertel 4127: 	    
1.207     albertel 4128: 	} else {
1.485     albertel 4129: 	    if ($display =~ /Problem Status/) {
                   4130: 		my $grade_status_mt = &mt('Grade Status');
                   4131: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4132: 	    }
                   4133: 	    my $part_mt = &mt('Part:');
                   4134: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4135: 	}
1.485     albertel 4136: 
1.474     albertel 4137: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4138:     }
1.474     albertel 4139:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4140: 
1.270     albertel 4141:     my %last_resets = 
                   4142: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4143: 
1.41      ng       4144:     #get info for each student
1.44      ng       4145:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 4146:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4147:     my $ctr = 0;
1.294     albertel 4148:     foreach (sort 
                   4149: 	     {
                   4150: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4151: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4152: 		 }
                   4153: 		 return $a cmp $b;
                   4154: 	     } (keys(%$fullname))) {
1.324     albertel 4155: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 4156:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       4157:     }
1.474     albertel 4158:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4159:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4160:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4161: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 4162:6):     if ($ctr == 0) {
1.442     banghart 4163:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 4164:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4165:6):                 '<span class="LC_warning">';
                   4166:6):         if ($env{'form.submitonly'} eq 'all') {
                   4167:6):             if (grep(/^all$/,@sections)) {
                   4168:6):                 if (grep(/^all$/,@groups)) {
                   4169:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4170:6):                                    $stu_status);
                   4171:6):                 } elsif (grep(/^none$/,@groups)) {
                   4172:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4173:6):                                    $stu_status);
                   4174:6):                 } else {
                   4175:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4176:6):                                    $group_display,$stu_status);
                   4177:6):                 }
                   4178:6):             } elsif (grep(/^none$/,@sections)) {
                   4179:6):                 if (grep(/^all$/,@groups)) {
                   4180:6):                     $result .= &mt('There are no students in no section 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 in no section and no group with enrollment status [_1] to modify or grade.',
                   4184:6):                                    $stu_status);
                   4185:6):                 } else {
                   4186:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4187:6):                                    $group_display,$stu_status);
                   4188:6):                 }
                   4189:6):             } else {
                   4190:6):                 if (grep(/^all$/,@groups)) {
                   4191:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4192:6):                                    $section_display,$stu_status);
                   4193:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 4194:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 4195:6):                                    $section_display,$stu_status);
                   4196:6):                 } else {
                   4197:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4198:6):                                    $section_display,$group_display,$stu_status);
                   4199:6):                 }
                   4200:6):             }
                   4201:6):         } else {
                   4202:6):             if (grep(/^all$/,@sections)) {
                   4203:6):                 if (grep(/^all$/,@groups)) {
                   4204:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4205:6):                                    $stu_status,$submission_status);
                   4206:6):                 } elsif (grep(/^none$/,@groups)) {
                   4207:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4208:6):                                    $stu_status,$submission_status);
                   4209:6):                 } else {
                   4210:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4211:6):                                    $group_display,$stu_status,$submission_status);
                   4212:6):                 }
                   4213:6):             } elsif (grep(/^none$/,@sections)) {
                   4214:6):                 if (grep(/^all$/,@groups)) {
                   4215:6):                     $result .= &mt('There are no students in no section 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 in no section and no group 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 no section 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):             } else {
                   4225:6):                 if (grep(/^all$/,@groups)) {
                   4226:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4227:6):                                    $section_display,$stu_status,$submission_status);
                   4228:6):                 } elsif (grep(/^none$/,@groups)) {
                   4229: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.',
                   4230:6):                                    $section_display,$stu_status,$submission_status);
                   4231:6):                 } else {
                   4232: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.',
                   4233:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4234:6):                 }
                   4235:6):             }
                   4236:6): 	}
                   4237:6): 	$result .= '</span><br />';
1.96      albertel 4238:     }
1.41      ng       4239:     return $result;
                   4240: }
                   4241: 
1.596.2.12.2.  7(raebur 4242:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4243: sub viewstudentgrade {
1.324     albertel 4244:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4245:     my ($uname,$udom) = split(/:/,$student);
                   4246:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4247:6):     my $submitonly = $env{'form.submitonly'};
                   4248:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4249:6):         my %partstatus = ();
                   4250:6):         if (ref($parts) eq 'ARRAY') {
                   4251:6):             foreach my $apart (@{$parts}) {
                   4252:6):                 my ($part,$type) = &split_part_type($apart);
                   4253:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4254:6):                 $status = 'nothing' if ($status eq '');
                   4255:6):                 $partstatus{$part}      = $status;
                   4256:6):                 my $subkey = "resource.$part.submitted_by";
                   4257:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4258:6):             }
                   4259:6):             my $submitted = 0;
                   4260:6):             my $graded = 0;
                   4261:6):             my $incorrect = 0;
                   4262:6):             foreach my $key (keys(%partstatus)) {
                   4263:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4264:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4265:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4266:6): 
                   4267:6):                 my $partid = (split(/\./,$key))[1];
                   4268:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4269:6):                     $submitted = 0;
                   4270:6):                 }
                   4271:6):             }
                   4272:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4273:6):                                        $submitonly eq 'incorrect' ||
                   4274:6):                                        $submitonly eq 'graded'));
                   4275:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4276:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4277:6):         }
                   4278:6):     }
                   4279:6):     if ($submitonly eq 'queued') {
                   4280:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4281:6):         my %queue_status =
                   4282:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4283:6):                                                     $udom,$uname);
                   4284:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4285:6):     }
                   4286:6):     $$ctr++;
                   4287:6):     my %aggregates = ();
1.474     albertel 4288:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4289:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4290:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4291: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4292: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4293: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4294:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4295:     foreach my $apart (@$parts) {
                   4296: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4297: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4298:         $result.='<td align="center">';
1.269     raeburn  4299:         my ($aggtries,$totaltries);
                   4300:         unless (exists($aggregates{$part})) {
1.270     albertel 4301: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4302: 
                   4303: 	    $aggtries = $totaltries;
1.269     raeburn  4304:             if ($$last_resets{$part}) {  
1.270     albertel 4305:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4306: 					   $part);
                   4307:             }
1.269     raeburn  4308:             $result.='<input type="hidden" name="'.
                   4309:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4310:             $result.='<input type="hidden" name="'.
                   4311:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4312:             $aggregates{$part} = 1;
                   4313:         }
1.41      ng       4314: 	if ($type eq 'awarded') {
1.320     albertel 4315: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4316: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4317: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4318: 	    $result.='<input type="text" name="'.
1.89      albertel 4319: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4320:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4321: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4322: 	} elsif ($type eq 'solved') {
                   4323: 	    my ($status,$foo)=split(/_/,$score,2);
                   4324: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4325: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4326: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4327: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4328: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4329:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4330: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4331: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4332: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4333: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4334: 	} else {
                   4335: 	    $result.='<input type="hidden" name="'.
                   4336: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4337: 		    "\n";
1.233     albertel 4338: 	    $result.='<input type="text" name="'.
1.122     ng       4339: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4340: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4341: 	}
                   4342:     }
1.474     albertel 4343:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4344:     return $result;
1.38      ng       4345: }
                   4346: 
1.44      ng       4347: #--- change scores for all the students in a section/class
                   4348: #    record does not get update if unchanged
1.38      ng       4349: sub editgrades {
1.596.2.12.2.  1(raebur 4350:0):     my ($request,$symb) = @_;
1.41      ng       4351: 
1.433     banghart 4352:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4353:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4354:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4355: 
1.477     albertel 4356:     my $result= &Apache::loncommon::start_data_table().
                   4357: 	&Apache::loncommon::start_data_table_header_row().
                   4358: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4359: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4360:     my %scoreptr = (
                   4361: 		    'correct'  =>'correct_by_override',
                   4362: 		    'incorrect'=>'incorrect_by_override',
                   4363: 		    'excused'  =>'excused',
                   4364: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4365:                     'credited' =>'credit_attempted',
1.43      ng       4366: 		    'nothing'  => '',
                   4367: 		    );
1.257     albertel 4368:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4369: 
1.44      ng       4370:     my (@partid);
                   4371:     my %weight = ();
1.54      albertel 4372:     my %columns = ();
1.44      ng       4373:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4374: 
1.582     raeburn  4375:     my $partserror;
                   4376:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4377:     if ($partserror) {
                   4378:         return &navmap_errormsg();
                   4379:     }
1.54      albertel 4380:     my $header;
1.257     albertel 4381:     while ($ctr < $env{'form.totalparts'}) {
                   4382: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4383: 	push(@partid,$partid);
1.257     albertel 4384: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4385: 	$ctr++;
1.54      albertel 4386:     }
1.324     albertel 4387:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.596.2.12.2.  2(raebur 4388:8):     my $totcolspan = 0;
1.54      albertel 4389:     foreach my $partid (@partid) {
1.478     albertel 4390: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4391: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4392: 	$columns{$partid}=2;
                   4393: 	foreach my $stores (@parts) {
                   4394: 	    my ($part,$type) = &split_part_type($stores);
                   4395: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4396: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4397: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4398: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4399:             my $narrowtext = &mt('Tries');
                   4400: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4401: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4402: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4403: 	    $columns{$partid}+=2;
                   4404: 	}
1.596.2.12.2.  2(raebur 4405:8):         $totcolspan += $columns{$partid};
1.54      albertel 4406:     }
                   4407:     foreach my $partid (@partid) {
1.324     albertel 4408: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4409: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4410: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4411: 	    '</th>';
1.54      albertel 4412: 
1.44      ng       4413:     }
1.477     albertel 4414:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4415: 	&Apache::loncommon::start_data_table_header_row().
                   4416: 	$header.
                   4417: 	&Apache::loncommon::end_data_table_header_row();
                   4418:     my @noupdate;
1.126     ng       4419:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4420:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4421: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4422: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4423: 	my %newrecord;
                   4424: 	my $updateflag = 0;
1.596.2.12.2.  2(raebur 4425:8):         my $usec=$classlist->{"$uname:$udom"}[5];
                   4426:8):         my $canmodify = &canmodify($usec);
                   4427:8):         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4428:8):                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4429:8):         if (!$canmodify) {
                   4430:8):             push(@noupdate,
                   4431:8):                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4432:8):                  &mt('Not allowed to modify student')."</span></td>");
                   4433:8):             next;
                   4434:8):         }
1.269     raeburn  4435:         my %aggregate = ();
                   4436:         my $aggregateflag = 0;
1.281     albertel 4437: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4438: 	foreach (@partid) {
1.257     albertel 4439: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4440: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4441: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4442: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4443: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4444: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4445: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4446: 	    my $score;
                   4447: 	    if ($partial eq '') {
1.257     albertel 4448: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4449: 	    } elsif ($partial > 0) {
                   4450: 		$score = 'correct_by_override';
                   4451: 	    } elsif ($partial == 0) {
                   4452: 		$score = 'incorrect_by_override';
                   4453: 	    }
1.257     albertel 4454: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4455: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4456: 
1.292     albertel 4457: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4458: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4459: 	    if ($dropMenu eq 'reset status' &&
                   4460: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4461: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4462: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4463: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4464: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4465: 		$updateflag = 1;
1.269     raeburn  4466:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4467:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4468:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4469:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4470:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4471:                     $aggregateflag = 1;
                   4472:                 }
1.139     albertel 4473: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4474: 		$updateflag = 1;
                   4475: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4476: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4477: 		$rec_update++;
1.125     ng       4478: 	    }
                   4479: 
1.93      albertel 4480: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4481: 		'<td align="center">'.$awarded.
                   4482: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4483: 
1.54      albertel 4484: 
                   4485: 	    my $partid=$_;
                   4486: 	    foreach my $stores (@parts) {
                   4487: 		my ($part,$type) = &split_part_type($stores);
                   4488: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4489: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4490: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4491: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4492: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4493: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4494: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4495: 		    $updateflag=1;
                   4496: 		}
1.93      albertel 4497: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4498: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4499: 	    }
1.44      ng       4500: 	}
1.477     albertel 4501: 	$line.="\n";
1.301     albertel 4502: 
                   4503: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4504: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4505: 
1.44      ng       4506: 	if ($updateflag) {
                   4507: 	    $count++;
1.257     albertel 4508: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4509: 				    $udom,$uname);
1.301     albertel 4510: 
                   4511: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4512: 					      $cnum,$udom,$uname)) {
                   4513: 		# need to figure out if should be in queue.
                   4514: 		my %record =  
                   4515: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4516: 					     $udom,$uname);
                   4517: 		my $all_graded = 1;
                   4518: 		my $none_graded = 1;
                   4519: 		foreach my $part (@parts) {
                   4520: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4521: 			$all_graded = 0;
                   4522: 		    } else {
                   4523: 			$none_graded = 0;
                   4524: 		    }
                   4525: 		}
                   4526: 
                   4527: 		if ($all_graded || $none_graded) {
                   4528: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4529: 							   $symb,$cdom,$cnum,
                   4530: 							   $udom,$uname);
                   4531: 		}
                   4532: 	    }
                   4533: 
1.477     albertel 4534: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4535: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4536: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4537: 	    $updateCtr++;
1.93      albertel 4538: 	} else {
1.477     albertel 4539: 	    push(@noupdate,
                   4540: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4541: 	    $noupdateCtr++;
1.44      ng       4542: 	}
1.269     raeburn  4543:         if ($aggregateflag) {
                   4544:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4545: 				  $cdom,$cnum);
1.269     raeburn  4546:         }
1.93      albertel 4547:     }
1.477     albertel 4548:     if (@noupdate) {
1.596.2.12.2.  2(raebur 4549:8):         my $numcols=$totcolspan+2;
1.477     albertel 4550: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4551: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4552: 	    &mt('No Changes Occurred For the Students Below').
                   4553: 	    '</td>'.
1.477     albertel 4554: 	    &Apache::loncommon::end_data_table_row();
                   4555: 	foreach my $line (@noupdate) {
                   4556: 	    $result.=
                   4557: 		&Apache::loncommon::start_data_table_row().
                   4558: 		$line.
                   4559: 		&Apache::loncommon::end_data_table_row();
                   4560: 	}
1.44      ng       4561:     }
1.596.2.12.2.  1(raebur 4562:0):     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4563:     my $msg = '<p><b>'.
                   4564: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4565: 	    $rec_update,$count).'</b><br />'.
                   4566: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4567: 	'</b></p>';
1.44      ng       4568:     return $title.$msg.$result;
1.5       albertel 4569: }
1.54      albertel 4570: 
                   4571: sub split_part_type {
                   4572:     my ($partstr) = @_;
                   4573:     my ($temp,@allparts)=split(/_/,$partstr);
                   4574:     my $type=pop(@allparts);
1.439     albertel 4575:     my $part=join('_',@allparts);
1.54      albertel 4576:     return ($part,$type);
                   4577: }
                   4578: 
1.44      ng       4579: #------------- end of section for handling grading by section/class ---------
                   4580: #
                   4581: #----------------------------------------------------------------------------
                   4582: 
1.5       albertel 4583: 
1.44      ng       4584: #----------------------------------------------------------------------------
                   4585: #
                   4586: #-------------------------- Next few routines handles grading by csv upload
                   4587: #
                   4588: #--- Javascript to handle csv upload
1.27      albertel 4589: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4590:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4591:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4592:6):   &js_escape(\$error1);
                   4593:6):   &js_escape(\$error2);
1.27      albertel 4594:   return(<<ENDPICK);
                   4595:   function verify(vf) {
                   4596:     var foundsomething=0;
                   4597:     var founduname=0;
1.243     albertel 4598:     var foundID=0;
1.27      albertel 4599:     for (i=0;i<=vf.nfields.value;i++) {
                   4600:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4601:       if (i==0 && tw!=0) { foundID=1; }
                   4602:       if (i==1 && tw!=0) { founduname=1; }
                   4603:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4604:     }
1.246     albertel 4605:     if (founduname==0 && foundID==0) {
                   4606: 	alert('$error1');
                   4607: 	return;
1.27      albertel 4608:     }
                   4609:     if (foundsomething==0) {
1.246     albertel 4610: 	alert('$error2');
                   4611: 	return;
1.27      albertel 4612:     }
                   4613:     vf.submit();
                   4614:   }
                   4615:   function flip(vf,tf) {
                   4616:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4617:     var i;
                   4618:     for (i=0;i<=vf.nfields.value;i++) {
                   4619:       //can not pick the same destination field for both name and domain
                   4620:       if (((i ==0)||(i ==1)) && 
                   4621:           ((tf==0)||(tf==1)) && 
                   4622:           (i!=tf) &&
                   4623:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4624:         eval('vf.f'+i+'.selectedIndex=0;')
                   4625:       }
                   4626:     }
                   4627:   }
                   4628: ENDPICK
                   4629: }
                   4630: 
                   4631: sub csvupload_javascript_forward_associate {
1.573     bisitz   4632:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4633:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4634:6):   &js_escape(\$error1);
                   4635:6):   &js_escape(\$error2);
1.27      albertel 4636:   return(<<ENDPICK);
                   4637:   function verify(vf) {
                   4638:     var foundsomething=0;
                   4639:     var founduname=0;
1.243     albertel 4640:     var foundID=0;
1.27      albertel 4641:     for (i=0;i<=vf.nfields.value;i++) {
                   4642:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4643:       if (tw==1) { foundID=1; }
                   4644:       if (tw==2) { founduname=1; }
                   4645:       if (tw>3) { foundsomething=1; }
1.27      albertel 4646:     }
1.246     albertel 4647:     if (founduname==0 && foundID==0) {
                   4648: 	alert('$error1');
                   4649: 	return;
1.27      albertel 4650:     }
                   4651:     if (foundsomething==0) {
1.246     albertel 4652: 	alert('$error2');
                   4653: 	return;
1.27      albertel 4654:     }
                   4655:     vf.submit();
                   4656:   }
                   4657:   function flip(vf,tf) {
                   4658:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4659:     var i;
                   4660:     //can not pick the same destination field twice
                   4661:     for (i=0;i<=vf.nfields.value;i++) {
                   4662:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4663:         eval('vf.f'+i+'.selectedIndex=0;')
                   4664:       }
                   4665:     }
                   4666:   }
                   4667: ENDPICK
                   4668: }
                   4669: 
1.26      albertel 4670: sub csvuploadmap_header {
1.324     albertel 4671:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4672:     my $javascript;
1.257     albertel 4673:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4674: 	$javascript=&csvupload_javascript_reverse_associate();
                   4675:     } else {
                   4676: 	$javascript=&csvupload_javascript_forward_associate();
                   4677:     }
1.45      ng       4678: 
1.257     albertel 4679:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4680:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4681:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 4682:0):     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4683:0):                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4684:0):                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4685:0):     my $reverse=&mt("Reverse Association");
1.41      ng       4686:     $request->print(<<ENDPICK);
1.596.2.12.2.  1(raebur 4687:0): <br />
                   4688:0): <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4689: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4690: <input type="hidden" name="associate"  value="" />
                   4691: <input type="hidden" name="phase"      value="three" />
                   4692: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4693: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4694: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4695: <input type="hidden" name="upfile_associate" 
1.257     albertel 4696:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4697: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4698: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4699: <hr />
                   4700: ENDPICK
1.596.2.12.2.  1(raebur 4701:0):     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4702:     return '';
1.26      albertel 4703: 
                   4704: }
                   4705: 
                   4706: sub csvupload_fields {
1.582     raeburn  4707:     my ($symb,$errorref) = @_;
                   4708:     my (@parts) = &getpartlist($symb,$errorref);
                   4709:     if (ref($errorref)) {
                   4710:         if ($$errorref) {
                   4711:             return;
                   4712:         }
                   4713:     }
                   4714: 
1.556     weissno  4715:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4716: 		['username','Student Username'],
                   4717: 		['domain','Student Domain']);
1.324     albertel 4718:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4719:     foreach my $part (sort(@parts)) {
                   4720: 	my @datum;
                   4721: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4722: 	my $name=$part;
                   4723: 	if  (!$display) { $display = $name; }
                   4724: 	@datum=($name,$display);
1.244     albertel 4725: 	if ($name=~/^stores_(.*)_awarded/) {
                   4726: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4727: 	}
1.41      ng       4728: 	push(@fields,\@datum);
                   4729:     }
                   4730:     return (@fields);
1.26      albertel 4731: }
                   4732: 
                   4733: sub csvuploadmap_footer {
1.41      ng       4734:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4735:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4736:     $request->print(<<ENDPICK);
1.26      albertel 4737: </table>
                   4738: <input type="hidden" name="nfields" value="$i" />
                   4739: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4740:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4741: </form>
                   4742: ENDPICK
                   4743: }
                   4744: 
1.283     albertel 4745: sub checkforfile_js {
1.539     riegler  4746:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4747:6):     &js_escape(\$alertmsg);
          1(raebur 4748:0):     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4749:     function checkUpload(formname) {
                   4750: 	if (formname.upfile.value == "") {
1.539     riegler  4751: 	    alert("$alertmsg");
1.86      ng       4752: 	    return false;
                   4753: 	}
                   4754: 	formname.submit();
                   4755:     }
                   4756: CSVFORMJS
1.283     albertel 4757:     return $result;
                   4758: }
                   4759: 
                   4760: sub upcsvScores_form {
1.596.2.12.2.  1(raebur 4761:0):     my ($request,$symb) = @_;
1.283     albertel 4762:     if (!$symb) {return '';}
                   4763:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 4764:0):     $result.=&Apache::loncommon::start_data_table().
                   4765:0):              &Apache::loncommon::start_data_table_header_row().
                   4766:0):              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4767:0):              &Apache::loncommon::end_data_table_header_row().
                   4768:0):              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4769:     my $upload=&mt("Upload Scores");
1.86      ng       4770:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4771:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4772:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4773:     $result.=<<ENDUPFORM;
1.106     albertel 4774: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4775: <input type="hidden" name="symb" value="$symb" />
                   4776: <input type="hidden" name="command" value="csvuploadmap" />
                   4777: $upfile_select
1.589     bisitz   4778: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4779: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4780: </form>
                   4781: ENDUPFORM
1.370     www      4782:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.596.2.12.2.  1(raebur 4783:0):                            &mt("How do I create a CSV file from a spreadsheet")).
                   4784:0):             '</td>'.
                   4785:0):             &Apache::loncommon::end_data_table_row().
                   4786:0):             &Apache::loncommon::end_data_table();
1.86      ng       4787:     return $result;
                   4788: }
                   4789: 
                   4790: 
1.26      albertel 4791: sub csvuploadmap {
1.596.2.12.2.  1(raebur 4792:0):     my ($request,$symb) = @_;
1.41      ng       4793:     if (!$symb) {return '';}
1.72      ng       4794: 
1.41      ng       4795:     my $datatoken;
1.257     albertel 4796:     if (!$env{'form.datatoken'}) {
1.41      ng       4797: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4798:     } else {
1.596.2.12.2.  3(raebur 4799:8):         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4800:8):         if ($datatoken ne '') { 
                   4801:8): 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4802:8):         }
1.26      albertel 4803:     }
1.41      ng       4804:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4805:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4806:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4807:     my ($i,$keyfields);
                   4808:     if (@records) {
1.582     raeburn  4809:         my $fieldserror;
                   4810: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4811:         if ($fieldserror) {
                   4812:             $request->print(&navmap_errormsg());
                   4813:             return;
                   4814:         }
1.257     albertel 4815: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4816: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4817: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4818: 							  \@fields);
                   4819: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4820: 	    chop($keyfields);
                   4821: 	} else {
                   4822: 	    unshift(@fields,['none','']);
                   4823: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4824: 							    \@fields);
1.311     banghart 4825:             foreach my $rec (@records) {
                   4826:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4827:                 if (%temp) {
                   4828:                     $keyfields=join(',',sort(keys(%temp)));
                   4829:                     last;
                   4830:                 }
                   4831:             }
1.41      ng       4832: 	}
                   4833:     }
                   4834:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4835: 
1.41      ng       4836:     return '';
1.27      albertel 4837: }
                   4838: 
1.246     albertel 4839: sub csvuploadoptions {
1.596.2.12.2.  1(raebur 4840:0):     my ($request,$symb)= @_;
                   4841:0):     my $overwrite=&mt('Overwrite any existing score');
1.257     albertel 4842:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4843:     my $ignore=&mt('Ignore First Line');
                   4844:     $request->print(<<ENDPICK);
                   4845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4846: <input type="hidden" name="command"    value="csvuploadassign" />
                   4847: <p>
                   4848: <label>
                   4849:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.596.2.12.2.  1(raebur 4850:0):    $overwrite
1.246     albertel 4851: </label>
                   4852: </p>
                   4853: ENDPICK
                   4854:     my %fields=&get_fields();
                   4855:     if (!defined($fields{'domain'})) {
1.257     albertel 4856: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.596.2.12.2.  1(raebur 4857:0):         $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4858:     }
1.257     albertel 4859:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4860: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4861: 	my $cleankey=$1;
                   4862: 	if ($cleankey eq 'command') { next; }
                   4863: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4864: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4865:     }
                   4866:     # FIXME do a check for any duplicated user ids...
                   4867:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4868:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4869: <hr /></form>'."\n");
1.246     albertel 4870:     return '';
                   4871: }
                   4872: 
                   4873: sub get_fields {
                   4874:     my %fields;
1.257     albertel 4875:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4876:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4877: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4878: 	    if ($env{'form.f'.$i} ne 'none') {
                   4879: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4880: 	    }
                   4881: 	} else {
1.257     albertel 4882: 	    if ($env{'form.f'.$i} ne 'none') {
                   4883: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4884: 	    }
                   4885: 	}
1.27      albertel 4886:     }
1.246     albertel 4887:     return %fields;
                   4888: }
                   4889: 
                   4890: sub csvuploadassign {
1.596.2.12.2.  1(raebur 4891:0):     my ($request,$symb) = @_;
1.246     albertel 4892:     if (!$symb) {return '';}
1.345     bowersj2 4893:     my $error_msg = '';
1.596.2.12.2.  3(raebur 4894:8):     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4895:8):     if ($datatoken ne '') {
                   4896:8):         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4897:8):     }
1.246     albertel 4898:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4899:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4900:     my %fields=&get_fields();
1.257     albertel 4901:     my $courseid=$env{'request.course.id'};
1.97      albertel 4902:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4903:     my @notallowed;
1.41      ng       4904:     my @skipped;
1.596.2.4  raeburn  4905:     my @warnings;
1.41      ng       4906:     my $countdone=0;
                   4907:     foreach my $grade (@gradedata) {
                   4908: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4909: 	my $domain;
                   4910: 	if ($entries{$fields{'domain'}}) {
                   4911: 	    $domain=$entries{$fields{'domain'}};
                   4912: 	} else {
1.257     albertel 4913: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4914: 	}
1.243     albertel 4915: 	$domain=~s/\s//g;
1.41      ng       4916: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4917: 	$username=~s/\s//g;
1.243     albertel 4918: 	if (!$username) {
                   4919: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4920: 	    $id=~s/\s//g;
1.243     albertel 4921: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4922: 	    $username=$ids{$id};
                   4923: 	}
1.41      ng       4924: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4925: 	    my $id=$entries{$fields{'ID'}};
                   4926: 	    $id=~s/\s//g;
                   4927: 	    if ($id) {
                   4928: 		push(@skipped,"$id:$domain");
                   4929: 	    } else {
                   4930: 		push(@skipped,"$username:$domain");
                   4931: 	    }
1.41      ng       4932: 	    next;
                   4933: 	}
1.108     albertel 4934: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4935: 	if (!&canmodify($usec)) {
                   4936: 	    push(@notallowed,"$username:$domain");
                   4937: 	    next;
                   4938: 	}
1.244     albertel 4939: 	my %points;
1.41      ng       4940: 	my %grades;
                   4941: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4942: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4943: 		$dest eq 'domain') { next; }
                   4944: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4945: 	    if ($dest=~/stores_(.*)_points/) {
                   4946: 		my $part=$1;
                   4947: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4948: 					      $symb,$domain,$username);
1.345     bowersj2 4949:                 if ($wgt) {
                   4950:                     $entries{$fields{$dest}}=~s/\s//g;
                   4951:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4952:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4953:                                           : 'correct_by_override';
1.596.2.4  raeburn  4954:                     if ($pcr>1) {
                   4955:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4956:                     }
1.345     bowersj2 4957:                     $grades{"resource.$part.awarded"}=$pcr;
                   4958:                     $grades{"resource.$part.solved"}=$award;
                   4959:                     $points{$part}=1;
                   4960:                 } else {
                   4961:                     $error_msg = "<br />" .
                   4962:                         &mt("Some point values were assigned"
                   4963:                             ." for problems with a weight "
                   4964:                             ."of zero. These values were "
                   4965:                             ."ignored.");
                   4966:                 }
1.244     albertel 4967: 	    } else {
                   4968: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4969: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4970: 		my $store_key=$dest;
                   4971: 		$store_key=~s/^stores/resource/;
                   4972: 		$store_key=~s/_/\./g;
                   4973: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4974: 	    }
1.41      ng       4975: 	}
1.596.2.12.2.  1(raebur 4976:0): 	if (! %grades) {
1.508     www      4977:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4978:         } else {
                   4979: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4980: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4981: 					   $env{'request.course.id'},
                   4982: 					   $domain,$username);
1.508     www      4983: 	   if ($result eq 'ok') {
1.596.2.12.2.  1(raebur 4984:0): # Successfully stored
1.508     www      4985: 	      $request->print('.');
1.596.2.4  raeburn  4986: # Remove from grading queue
                   4987:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4988:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4989:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4990:                                              $domain,$username);
1.508     www      4991: 	   } else {
                   4992: 	      $request->print("<p><span class=\"LC_error\">".
                   4993:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4994:                                   "$username:$domain",$result)."</span></p>");
                   4995: 	   }
                   4996: 	   $request->rflush();
                   4997: 	   $countdone++;
                   4998:         }
1.41      ng       4999:     }
1.570     www      5000:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  5001:     if (@warnings) {
                   5002:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5003:         $request->print(join(', ',@warnings));
                   5004:     }
1.41      ng       5005:     if (@skipped) {
1.571     www      5006: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5007:         $request->print(join(', ',@skipped));
1.106     albertel 5008:     }
                   5009:     if (@notallowed) {
1.571     www      5010: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5011: 	$request->print(join(', ',@notallowed));
1.41      ng       5012:     }
1.106     albertel 5013:     $request->print("<br />\n");
1.345     bowersj2 5014:     return $error_msg;
1.26      albertel 5015: }
1.44      ng       5016: #------------- end of section for handling csv file upload ---------
                   5017: #
                   5018: #-------------------------------------------------------------------
                   5019: #
1.122     ng       5020: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5021: #
                   5022: #--- Select a page/sequence and a student to grade
1.68      ng       5023: sub pickStudentPage {
1.596.2.12.2.  1(raebur 5024:0):     my ($request,$symb) = @_;
1.68      ng       5025: 
1.539     riegler  5026:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 5027:6):     &js_escape(\$alertmsg);
          1(raebur 5028:0):     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5029: 
                   5030: function checkPickOne(formname) {
1.76      ng       5031:     if (radioSelection(formname.student) == null) {
1.539     riegler  5032: 	alert("$alertmsg");
1.68      ng       5033: 	return;
                   5034:     }
1.125     ng       5035:     ptr = pullDownSelection(formname.selectpage);
                   5036:     formname.page.value = formname["page"+ptr].value;
                   5037:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5038:     formname.submit();
                   5039: }
                   5040: 
                   5041: LISTJAVASCRIPT
1.118     ng       5042:     &commonJSfunctions($request);
1.596.2.12.2.  1(raebur 5043:0): 
1.257     albertel 5044:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5045:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5046:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.596.2.12.2.  8(raebur 5047:9):     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5048: 
1.398     albertel 5049:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5050: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5051: 
1.80      ng       5052:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5053:     my $map_error;
                   5054:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5055:     if ($map_error) {
                   5056:         $request->print(&navmap_errormsg());
                   5057:         return; 
                   5058:     }
1.137     albertel 5059:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5060: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5061: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 5062: 
1.596.2.12.2.  1(raebur 5063:0):     # Collection of hidden fields
                   5064:0):     my $ctr=0;
1.70      ng       5065:     foreach (@$titles) {
                   5066: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5067: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5068: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5069: 	$ctr++;
                   5070:     }
1.72      ng       5071:     $result.='<input type="hidden" name="page" />'."\n".
                   5072: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       5073: 
1.432     banghart 5074:     $result.=&build_section_inputs();
1.442     banghart 5075:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5076:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.596.2.12.2.  1(raebur 5077:0):         '<input type="hidden" name="command" value="displayPage" />'."\n".
                   5078:0):         '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   5079:0): 
                   5080:0):     # Show grading options
                   5081:0):     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5082:0):     my $select = '<select name="selectpage">'."\n";
                   5083:0):     $ctr=0;
                   5084:0):     foreach (@$titles) {
                   5085:0):         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5086:0):         $select.='<option value="'.$ctr.'"'.
                   5087:0):             ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5088:0):             '>'.$showtitle.'</option>'."\n";
                   5089:0):         $ctr++;
                   5090:0):     }
                   5091:0):     $select.= '</select>';
1.72      ng       5092: 
1.596.2.12.2.  1(raebur 5093:0):     $result.=
                   5094:0):         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5095:0):        .$select
                   5096:0):        .&Apache::lonhtmlcommon::row_closure();
                   5097:0): 
                   5098:0):     $result.=
                   5099:0):         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5100:0):        .'<label><input type="radio" name="vProb" value="no"'
                   5101:0):            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5102:0):        .'<label><input type="radio" name="vProb" value="yes" />'
                   5103:0):            .&mt('yes').'</label>'."\n"
                   5104:0):        .&Apache::lonhtmlcommon::row_closure();
                   5105:0): 
                   5106:0):     $result.=
                   5107:0):         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5108:0):        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5109:0):            .&mt('none').' </label>'."\n"
                   5110:0):        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5111:0):            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5112:0):        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5113:0):            .&mt('all submissions with details').' </label>'
                   5114:0):        .&Apache::lonhtmlcommon::row_closure();
                   5115:0): 
                   5116:0):     $result.=
                   5117:0):         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5118:0):        .'<input type="text" name="CODE" value="" />'
                   5119:0):        .&Apache::lonhtmlcommon::row_closure(1)
                   5120:0):        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5121: 
1.596.2.12.2.  1(raebur 5122:0):     # Show list of students to select for grading
                   5123:0):     $result.='<br /><input type="button" '.
1.589     bisitz   5124:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5125: 
1.68      ng       5126:     $request->print($result);
                   5127: 
1.485     albertel 5128:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5129: 	&Apache::loncommon::start_data_table().
                   5130: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5131: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5132: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5133: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5134: 	'<th>'.&nameUserString('header').'</th>'.
                   5135: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5136:  
1.596.2.12.2.  8(raebur 5137:9):     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5138:     my $ptr = 1;
1.294     albertel 5139:     foreach my $student (sort 
                   5140: 			 {
                   5141: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5142: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5143: 			     }
                   5144: 			     return $a cmp $b;
                   5145: 			 } (keys(%$fullname))) {
1.68      ng       5146: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5147: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5148:                                   : '</td>');
1.126     ng       5149: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5150: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5151: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5152: 	$studentTable.=
                   5153: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5154:                          : '');
1.68      ng       5155: 	$ptr++;
                   5156:     }
1.484     albertel 5157:     if ($ptr%2 == 0) {
                   5158: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5159: 	    &Apache::loncommon::end_data_table_row();
                   5160:     }
                   5161:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5162:     $studentTable.='<input type="button" '.
1.589     bisitz   5163:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5164: 
                   5165:     $request->print($studentTable);
                   5166: 
                   5167:     return '';
                   5168: }
                   5169: 
                   5170: sub getSymbMap {
1.582     raeburn  5171:     my ($map_error) = @_;
1.132     bowersj2 5172:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5173:     unless (ref($navmap)) {
                   5174:         if (ref($map_error)) {
                   5175:             $$map_error = 'navmap';
                   5176:         }
                   5177:         return;
                   5178:     }
1.68      ng       5179:     my %symbx = ();
                   5180:     my @titles = ();
1.117     bowersj2 5181:     my $minder = 0;
                   5182: 
                   5183:     # Gather every sequence that has problems.
1.240     albertel 5184:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5185: 					       1,0,1);
1.117     bowersj2 5186:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 5187: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 5188: 	    my $title = $minder.'.'.
                   5189: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5190: 	    push(@titles, $title); # minder in case two titles are identical
                   5191: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5192: 	    $minder++;
1.241     albertel 5193: 	}
1.68      ng       5194:     }
                   5195:     return \@titles,\%symbx;
                   5196: }
                   5197: 
1.72      ng       5198: #
                   5199: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5200: sub displayPage {
1.596.2.12.2.  1(raebur 5201:0):     my ($request,$symb) = @_;
1.257     albertel 5202:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5203:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5204:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5205:     my $pageTitle = $env{'form.page'};
1.103     albertel 5206:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5207:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5208:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5209: 
                   5210:     #need to make sure we have the correct data for later EXT calls, 
                   5211:     #thus invalidate the cache
                   5212:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5213:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5214:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5215:     &Apache::lonnet::clear_EXT_cache_status();
                   5216: 
1.103     albertel 5217:     if (!&canview($usec)) {
1.596.2.12.2.  1(raebur 5218:0): 	$request->print(
                   5219:0):             '<span class="LC_warning">'.
                   5220:0):             &mt('Unable to view requested student. ([_1])',
                   5221:0):                 $env{'form.student'}).
                   5222:0):             '</span>');
          8(raebur 5223:4):         return;
1.103     albertel 5224:     }
1.398     albertel 5225:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5226:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5227: 	'</h3>'."\n";
1.500     albertel 5228:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5229:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5230: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5231:     } else {
                   5232: 	delete($env{'form.CODE'});
                   5233:     }
1.71      ng       5234:     &sub_page_js($request);
                   5235:     $request->print($result);
                   5236: 
1.132     bowersj2 5237:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5238:     unless (ref($navmap)) {
                   5239:         $request->print(&navmap_errormsg());
                   5240:         return;
                   5241:     }
1.257     albertel 5242:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5243:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5244:     if (!$map) {
1.485     albertel 5245: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5246: 	return; 
                   5247:     }
1.68      ng       5248:     my $iterator = $navmap->getIterator($map->map_start(),
                   5249: 					$map->map_finish());
                   5250: 
1.71      ng       5251:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5252: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5253: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5254: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5255: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5256: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5257: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.596.2.12.2.  1(raebur 5258:0): 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5259: 
1.382     albertel 5260:     if (defined($env{'form.CODE'})) {
                   5261: 	$studentTable.=
                   5262: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5263:     }
1.381     albertel 5264:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5265: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5266: 
1.594     bisitz   5267:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5268:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5269:         '</span>'."\n".
1.484     albertel 5270: 	&Apache::loncommon::start_data_table().
                   5271: 	&Apache::loncommon::start_data_table_header_row().
1.596.2.12.2.  1(raebur 5272:0): 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5273: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5274: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5275: 
1.329     albertel 5276:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5277:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5278:     $iterator->next(); # skip the first BEGIN_MAP
                   5279:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5280:     while ($depth > 0) {
1.68      ng       5281:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5282:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5283: 
1.385     albertel 5284:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5285: 	    my $parts = $curRes->parts();
1.68      ng       5286:             my $title = $curRes->compTitle();
1.71      ng       5287: 	    my $symbx = $curRes->symb();
1.484     albertel 5288: 	    $studentTable.=
                   5289: 		&Apache::loncommon::start_data_table_row().
                   5290: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5291: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5292:2): 		                        : '<br />('.&mt('[_1]parts',
                   5293:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5294: 		 ).
                   5295: 		 '</td>';
1.71      ng       5296: 	    $studentTable.='<td valign="top">';
1.382     albertel 5297: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5298: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5299: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5300: 					     undef,'both',\%form);
1.71      ng       5301: 	    } else {
1.382     albertel 5302: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5303: 		$companswer =~ s|<form(.*?)>||g;
                   5304: 		$companswer =~ s|</form>||g;
1.71      ng       5305: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5306: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5307: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5308: #		}
1.116     ng       5309: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5310: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5311: 	    }
                   5312: 
1.257     albertel 5313: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5314: 
1.257     albertel 5315: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5316: 		if ($record{'version'} eq '') {
1.485     albertel 5317: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5318: 		} else {
1.116     ng       5319: 		    my %responseType = ();
                   5320: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5321: 			my @responseIds =$curRes->responseIds($partid);
                   5322: 			my @responseType =$curRes->responseType($partid);
                   5323: 			my %responseIds;
                   5324: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5325: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5326: 			}
                   5327: 			$responseType{$partid} = \%responseIds;
1.116     ng       5328: 		    }
1.148     albertel 5329: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5330: 
1.71      ng       5331: 		}
1.257     albertel 5332: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5333: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5334:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5335: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5336: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5337:5): 									'','.submission',undef,
                   5338:5):                                                                         $usec,$identifier);
1.71      ng       5339:  
                   5340: 	    }
1.103     albertel 5341: 	    if (&canmodify($usec)) {
1.585     bisitz   5342:             $studentTable.=&gradeBox_start();
1.103     albertel 5343: 		foreach my $partid (@{$parts}) {
                   5344: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5345: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5346: 		    $question++;
                   5347: 		}
1.585     bisitz   5348:             $studentTable.=&gradeBox_end();
1.196     albertel 5349: 		$prob++;
1.71      ng       5350: 	    }
                   5351: 	    $studentTable.='</td></tr>';
1.68      ng       5352: 
1.103     albertel 5353: 	}
1.68      ng       5354:         $curRes = $iterator->next();
                   5355:     }
                   5356: 
1.589     bisitz   5357:     $studentTable.=
                   5358:         '</table>'."\n".
                   5359:         '<input type="button" value="'.&mt('Save').'" '.
                   5360:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5361:         '</form>'."\n";
1.71      ng       5362:     $request->print($studentTable);
                   5363: 
                   5364:     return '';
1.119     ng       5365: }
                   5366: 
                   5367: sub displaySubByDates {
1.148     albertel 5368:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5369:     my $isCODE=0;
1.335     albertel 5370:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5371:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5372:     my $studentTable=&Apache::loncommon::start_data_table().
                   5373: 	&Apache::loncommon::start_data_table_header_row().
                   5374: 	'<th>'.&mt('Date/Time').'</th>'.
                   5375: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5376:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5377: 	'<th>'.&mt('Submission').'</th>'.
                   5378: 	'<th>'.&mt('Status').'</th>'.
                   5379: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5380:     my ($version);
                   5381:     my %mark;
1.148     albertel 5382:     my %orders;
1.119     ng       5383:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5384:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5385: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5386:     }
1.335     albertel 5387: 
                   5388:     my $interaction;
1.525     raeburn  5389:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5390:5):     my (%lastrndseed,%lasttype);
1.119     ng       5391:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5392: 	my $timestamp = 
                   5393: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5394: 	if (exists($$record{$version.':resource.0.version'})) {
                   5395: 	    $interaction = $$record{$version.':resource.0.version'};
                   5396: 	}
1.596.2.12.2.  (raeburn 5397:):         if ($isTask && $env{'form.previousversion'}) {
                   5398:):             next unless ($interaction == $env{'form.previousversion'});
                   5399:):         }
1.335     albertel 5400: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5401: 		             : "$version:resource");
1.467     albertel 5402: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5403: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5404: 	if ($isCODE) {
                   5405: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5406: 	}
1.596.2.12.2.  (raeburn 5407:):         if ($isTask) {
                   5408:):             $studentTable.='<td>'.$interaction.'</td>';
                   5409:):         }
1.119     ng       5410: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5411: 	my @displaySub = ();
                   5412: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5413:             my ($hidden,$type);
                   5414:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5415:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5416:                 $hidden = 1;
                   5417:             }
1.596.2.12.2.  1(raebur 5418:0): 	    my @matchKey;
                   5419:0):             if ($isTask) {
                   5420:0):                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
                   5421:0):             } else {
                   5422:0): 		@matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5423:0):             }
1.122     ng       5424: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5425: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5426: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5427: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5428: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5429:                     
1.335     albertel 5430: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5431: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5432:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5433:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5434:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5435:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5436:                                    .'</span>'
                   5437:                                    .' <b>';
1.596     raeburn  5438:                     if ($hidden) {
                   5439:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5440:                     } else {
1.596.2.2  raeburn  5441:                         my ($trial,$rndseed,$newvariation);
                   5442:                         if ($type eq 'randomizetry') {
                   5443:                             $trial = $$record{"$where.$partid.tries"};
                   5444:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5445:                         }
1.596     raeburn  5446: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5447: 			    $displaySub[0].=&mt('Trial not counted');
                   5448: 		        } else {
                   5449: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5450: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5451:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5452:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5453:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5454:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5455:                                 }
                   5456:                             }
1.596.2.12.2.  4(raebur 5457:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5458:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5459: 		        }
                   5460: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5461:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5462: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5463: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5464: 			    $orders{$partid}->{$responseId}=
                   5465: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5466:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5467: 		        }
1.596.2.2  raeburn  5468: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5469: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5470: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5471:                     }
1.147     albertel 5472: 		}
                   5473: 	    }
1.335     albertel 5474: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5475: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5476: 				    $$record{"$where.$partid.checkedin"},
                   5477: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5478: 					'<br />';
1.335     albertel 5479: 	    }
                   5480: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5481: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5482: 		    lc($$record{"$where.$partid.award"}).' '.
                   5483: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5484: 		    '<br />';
                   5485: 	    }
1.335     albertel 5486: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5487: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5488: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5489: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5490: 		$displaySub[2].=
                   5491: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5492: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5493: 	    }
                   5494: 	}
                   5495: 	# needed because old essay regrader has not parts info
                   5496: 	if (exists $$record{"$version:resource.regrader"}) {
                   5497: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5498: 	}
                   5499: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5500: 	if ($displaySub[2]) {
1.467     albertel 5501: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5502: 	}
1.467     albertel 5503: 	$studentTable.='&nbsp;</td>'.
                   5504: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5505:     }
1.467     albertel 5506:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5507:     return $studentTable;
1.71      ng       5508: }
                   5509: 
                   5510: sub updateGradeByPage {
1.596.2.12.2.  1(raebur 5511:0):     my ($request,$symb) = @_;
1.71      ng       5512: 
1.257     albertel 5513:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5514:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5515:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5516:     my $pageTitle = $env{'form.page'};
1.103     albertel 5517:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5518:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5519:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5520:     if (!&canmodify($usec)) {
1.526     raeburn  5521: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5522: 	return;
                   5523:     }
1.398     albertel 5524:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5525:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5526: 	'</h3>'."\n";
1.70      ng       5527: 
1.68      ng       5528:     $request->print($result);
                   5529: 
1.582     raeburn  5530: 
1.132     bowersj2 5531:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5532:     unless (ref($navmap)) {
                   5533:         $request->print(&navmap_errormsg());
                   5534:         return;
                   5535:     }
1.257     albertel 5536:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5537:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5538:     if (!$map) {
1.527     raeburn  5539: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5540: 	return; 
                   5541:     }
1.71      ng       5542:     my $iterator = $navmap->getIterator($map->map_start(),
                   5543: 					$map->map_finish());
1.70      ng       5544: 
1.484     albertel 5545:     my $studentTable=
                   5546: 	&Apache::loncommon::start_data_table().
                   5547: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5548: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5549: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5550: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5551: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5552: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5553: 
                   5554:     $iterator->next(); # skip the first BEGIN_MAP
                   5555:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5556:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5557:     while ($depth > 0) {
1.71      ng       5558:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5559:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5560: 
1.385     albertel 5561:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5562: 	    my $parts = $curRes->parts();
1.71      ng       5563:             my $title = $curRes->compTitle();
                   5564: 	    my $symbx = $curRes->symb();
1.484     albertel 5565: 	    $studentTable.=
                   5566: 		&Apache::loncommon::start_data_table_row().
                   5567: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5568: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5569:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5570: 		.')').'</td>';
1.71      ng       5571: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5572: 
                   5573: 	    my %newrecord=();
                   5574: 	    my @displayPts=();
1.269     raeburn  5575:             my %aggregate = ();
                   5576:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5577:5):             if ($env{'form.HIDE'.$prob}) {
                   5578:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5579:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5580:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5581:5):                 $hideflag += $numchgs;
                   5582:5):             }
1.71      ng       5583: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5584: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5585: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5586: 
1.257     albertel 5587: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5588: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5589: 		my $partial = $newpts/$wgt;
                   5590: 		my $score;
                   5591: 		if ($partial > 0) {
                   5592: 		    $score = 'correct_by_override';
1.125     ng       5593: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5594: 		    $score = 'incorrect_by_override';
                   5595: 		}
1.257     albertel 5596: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5597: 		if ($dropMenu eq 'excused') {
1.71      ng       5598: 		    $partial = '';
                   5599: 		    $score = 'excused';
1.125     ng       5600: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5601: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5602: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5603: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5604: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5605: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5606: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5607: 		    $changeflag++;
                   5608: 		    $newpts = '';
1.269     raeburn  5609:                     
                   5610:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5611:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5612:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5613:                     if ($aggtries > 0) {
                   5614:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5615:                         $aggregateflag = 1;
                   5616:                     }
1.71      ng       5617: 		}
1.324     albertel 5618: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5619: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5620: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5621: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5622: 		    '&nbsp;<br />';
1.526     raeburn  5623: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5624: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5625: 		    '&nbsp;<br />';
1.71      ng       5626: 		$question++;
1.380     albertel 5627: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5628: 
1.71      ng       5629: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5630: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5631: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5632: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5633: 
                   5634: 		$changeflag++;
                   5635: 	    }
                   5636: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5637: 		my %record = 
                   5638: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5639: 					     $udom,$uname);
                   5640: 
                   5641: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5642: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5643: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5644: 		    $newrecord{'resource.CODE'} = '';
                   5645: 		}
1.257     albertel 5646: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5647: 					$udom,$uname);
1.382     albertel 5648: 		%record = &Apache::lonnet::restore($symbx,
                   5649: 						   $env{'request.course.id'},
                   5650: 						   $udom,$uname);
1.380     albertel 5651: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5652: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5653: 	    }
1.380     albertel 5654: 	    
1.269     raeburn  5655:             if ($aggregateflag) {
                   5656:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5657:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5658:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5659:             }
1.125     ng       5660: 
1.71      ng       5661: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5662: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5663: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5664: 
1.196     albertel 5665: 	    $prob++;
1.68      ng       5666: 	}
1.71      ng       5667:         $curRes = $iterator->next();
1.68      ng       5668:     }
1.98      albertel 5669: 
1.484     albertel 5670:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5671:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5672: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5673:5): 		  $changeflag).'<br />');
                   5674:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5675:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5676:5):                      $hideflag).'<br />');
                   5677:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5678: 
1.70      ng       5679:     return '';
                   5680: }
                   5681: 
1.72      ng       5682: #-------- end of section for handling grading by page/sequence ---------
                   5683: #
                   5684: #-------------------------------------------------------------------
                   5685: 
1.581     www      5686: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5687: #
                   5688: #------ start of section for handling grading by page/sequence ---------
                   5689: 
1.423     albertel 5690: =pod
                   5691: 
                   5692: =head1 Bubble sheet grading routines
                   5693: 
1.424     albertel 5694:   For this documentation:
                   5695: 
                   5696:    'scanline' refers to the full line of characters
                   5697:    from the file that we are parsing that represents one entire sheet
                   5698: 
                   5699:    'bubble line' refers to the data
1.596.2.6  raeburn  5700:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5701: 
                   5702: 
1.596.2.6  raeburn  5703: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5704: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5705: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5706: one of the predefined configurations for what each scanline looks
                   5707: like.
                   5708: 
                   5709: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5710: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5711: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5712:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5713: invalid student/employee ID
1.424     albertel 5714: 
                   5715: If the CODE option is used that determines the randomization of the
1.556     weissno  5716: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5717: username:domain.
                   5718: 
                   5719: During the validation phase the instructor can choose to skip scanlines. 
                   5720: 
1.596.2.6  raeburn  5721: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5722: 
                   5723:   scantron_original_filename (unmodified original file)
                   5724:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5725:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5726: 
                   5727: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5728: correction information that isn't representable in the bubblesheet
1.424     albertel 5729: file (see &scantron_getfile() for more information)
                   5730: 
                   5731: After all scanlines are either valid, marked as valid or skipped, then
                   5732: foreach line foreach problem in the picked sequence, an ssi request is
                   5733: made that simulates a user submitting their selected letter(s) against
                   5734: the homework problem.
1.423     albertel 5735: 
                   5736: =over 4
                   5737: 
                   5738: 
                   5739: 
                   5740: =item defaultFormData
                   5741: 
                   5742:   Returns html hidden inputs used to hold context/default values.
                   5743: 
                   5744:  Arguments:
                   5745:   $symb - $symb of the current resource 
                   5746: 
                   5747: =cut
1.422     foxr     5748: 
1.81      albertel 5749: sub defaultFormData {
1.324     albertel 5750:     my ($symb)=@_;
1.596.2.12.2.  1(raebur 5751:0):     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5752: }
                   5753: 
1.447     foxr     5754: 
1.423     albertel 5755: =pod 
                   5756: 
                   5757: =item getSequenceDropDown
                   5758: 
                   5759:    Return html dropdown of possible sequences to grade
                   5760:  
                   5761:  Arguments:
1.582     raeburn  5762:    $symb - $symb of the current resource
                   5763:    $map_error - ref to scalar which will container error if
                   5764:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5765: 
                   5766: =cut
1.422     foxr     5767: 
1.75      albertel 5768: sub getSequenceDropDown {
1.582     raeburn  5769:     my ($symb,$map_error)=@_;
1.75      albertel 5770:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5771:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5772:     if (ref($map_error)) {
                   5773:         return if ($$map_error);
                   5774:     }
1.137     albertel 5775:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5776:     my $ctr=0;
                   5777:     foreach (@$titles) {
                   5778: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5779: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5780: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5781: 	    '>'.$showtitle.'</option>'."\n";
                   5782: 	$ctr++;
                   5783:     }
                   5784:     $result.= '</select>';
                   5785:     return $result;
                   5786: }
                   5787: 
1.495     albertel 5788: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5789:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5790: 
                   5791: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5792: 
1.509     raeburn  5793: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5794:                                    # matchresponse or rankresponse, where 
                   5795:                                    # an individual response can have multiple 
                   5796:                                    # lines
1.503     raeburn  5797: 
                   5798: my %responsetype_per_response;     # responsetype for each response
                   5799: 
1.596.2.12.2.  6(raebur 5800:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5801:3):                                    # numbered response. Needed when randomorder
                   5802:3):                                    # or randompick are in use. Key is ID, value 
                   5803:3):                                    # is response number.
                   5804:3): 
1.495     albertel 5805: # Save and restore the bubble lines array to the form env.
                   5806: 
                   5807: 
                   5808: sub save_bubble_lines {
                   5809:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5810: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5811: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5812: 	    $first_bubble_line{$line};
1.503     raeburn  5813:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5814:             $subdivided_bubble_lines{$line};
                   5815:         $env{"form.scantron.responsetype.$line"} =
                   5816:             $responsetype_per_response{$line};
1.495     albertel 5817:     }
1.596.2.12.2.  6(raebur 5818:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5819:3):         my $line = $masterseq_id_responsenum{$resid};
                   5820:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5821:3):     }
1.495     albertel 5822: }
                   5823: 
                   5824: 
                   5825: sub restore_bubble_lines {
                   5826:     my $line = 0;
                   5827:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5828:3):     %masterseq_id_responsenum = ();
1.495     albertel 5829:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5830: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5831: 	$bubble_lines_per_response{$line} = $value;
                   5832: 	$first_bubble_line{$line}  =
                   5833: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5834:         $subdivided_bubble_lines{$line} =
                   5835:             $env{"form.scantron.sub_bubblelines.$line"};
                   5836:         $responsetype_per_response{$line} =
                   5837:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5838:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5839:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5840: 	$line++;
                   5841:     }
                   5842: }
                   5843: 
1.423     albertel 5844: =pod 
                   5845: 
                   5846: =item scantron_filenames
                   5847: 
                   5848:    Returns a list of the scantron files in the current course 
                   5849: 
                   5850: =cut
1.422     foxr     5851: 
1.202     albertel 5852: sub scantron_filenames {
1.257     albertel 5853:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5854:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5855:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5856:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5857:):                                                         $cname,$getpropath);
1.202     albertel 5858:     my @possiblenames;
1.596.2.12.2.  (raeburn 5859:):     if (ref($dirlist) eq 'ARRAY') {
                   5860:):         foreach my $filename (sort(@{$dirlist})) {
                   5861:): 	    ($filename)=split(/&/,$filename);
                   5862:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5863:): 	    $filename=~s/^scantron_orig_//;
                   5864:): 	    push(@possiblenames,$filename);
                   5865:):         }
1.202     albertel 5866:     }
                   5867:     return @possiblenames;
                   5868: }
                   5869: 
1.423     albertel 5870: =pod 
                   5871: 
                   5872: =item scantron_uploads
                   5873: 
                   5874:    Returns  html drop-down list of scantron files in current course.
                   5875: 
                   5876:  Arguments:
                   5877:    $file2grade - filename to set as selected in the dropdown
                   5878: 
                   5879: =cut
1.422     foxr     5880: 
1.202     albertel 5881: sub scantron_uploads {
1.209     ng       5882:     my ($file2grade) = @_;
1.202     albertel 5883:     my $result=	'<select name="scantron_selectfile">';
                   5884:     $result.="<option></option>";
                   5885:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5886: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5887:     }
                   5888:     $result.="</select>";
                   5889:     return $result;
                   5890: }
                   5891: 
1.423     albertel 5892: =pod 
                   5893: 
                   5894: =item scantron_scantab
                   5895: 
                   5896:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5897:   file.
                   5898: 
                   5899: =cut
1.422     foxr     5900: 
1.82      albertel 5901: sub scantron_scantab {
                   5902:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5903:     $result.='<option></option>'."\n";
1.596.2.12.2.  9(raebur 5904:9):     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5905:     if (@lines > 0) {
                   5906:         foreach my $line (@lines) {
                   5907:             next if (($line =~ /^\#/) || ($line eq ''));
                   5908: 	    my ($name,$descrip)=split(/:/,$line);
                   5909: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5910:         }
1.82      albertel 5911:     }
                   5912:     $result.='</select>'."\n";
1.518     raeburn  5913:     return $result;
                   5914: }
                   5915: 
1.423     albertel 5916: =pod 
                   5917: 
                   5918: =item scantron_CODElist
                   5919: 
                   5920:   Returns html drop down of the saved CODE lists from current course,
                   5921:   generated from earlier printings.
                   5922: 
                   5923: =cut
1.422     foxr     5924: 
1.186     albertel 5925: sub scantron_CODElist {
1.257     albertel 5926:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5927:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5928:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5929:     my $namechoice='<option></option>';
1.225     albertel 5930:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5931: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5932: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5933: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5934:     }
                   5935:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5936:     return $namechoice;
                   5937: }
                   5938: 
1.423     albertel 5939: =pod 
                   5940: 
                   5941: =item scantron_CODEunique
                   5942: 
                   5943:   Returns the html for "Each CODE to be used once" radio.
                   5944: 
                   5945: =cut
1.422     foxr     5946: 
1.186     albertel 5947: sub scantron_CODEunique {
1.532     bisitz   5948:     my $result='<span class="LC_nobreak">
1.272     albertel 5949:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5950:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5951:                 </span>
1.532     bisitz   5952:                 <span class="LC_nobreak">
1.272     albertel 5953:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5954:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5955:                 </span>';
1.186     albertel 5956:     return $result;
                   5957: }
1.423     albertel 5958: 
                   5959: =pod 
                   5960: 
                   5961: =item scantron_selectphase
                   5962: 
1.596.2.6  raeburn  5963:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5964:   Allows for - starting a grading run.
1.424     albertel 5965:              - downloading existing scan data (original, corrected
1.423     albertel 5966:                                                 or skipped info)
                   5967: 
                   5968:              - uploading new scan data
                   5969: 
                   5970:  Arguments:
                   5971:   $r          - The Apache request object
                   5972:   $file2grade - name of the file that contain the scanned data to score
                   5973: 
                   5974: =cut
1.186     albertel 5975: 
1.75      albertel 5976: sub scantron_selectphase {
1.596.2.12.2.  1(raebur 5977:0):     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5978:     if (!$symb) {return '';}
1.582     raeburn  5979:     my $map_error;
                   5980:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5981:     if ($map_error) {
                   5982:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5983:         return;
                   5984:     }
1.324     albertel 5985:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5986:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5987:     my $format_selector=&scantron_scantab();
1.186     albertel 5988:     my $CODE_selector=&scantron_CODElist();
                   5989:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5990:     my $result;
1.422     foxr     5991: 
1.513     foxr     5992:     $ssi_error = 0;
                   5993: 
1.596.2.4  raeburn  5994:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5995:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5996: 
                   5997:         # Chunk of form to prompt for a scantron file upload.
                   5998: 
                   5999:         $r->print('
1.596.2.12.2.  9(raebur 6000:9):     <br />');
                   6001:9):         my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6002:9):         my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   6003:9):         my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6004:9):         &js_escape(\$alertmsg);
                   6005:9):         my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
                   6006:9):         $r->print(&Apache::lonhtmlcommon::scripttag('
1.596.2.4  raeburn  6007:     function checkUpload(formname) {
                   6008:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 6009:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  6010:             return false;
                   6011:         }
                   6012:         formname.submit();
1.596.2.12.2.  9(raebur 6013:9):     }'."\n".$formatjs));
                   6014:9):         $r->print('
1.596.2.4  raeburn  6015:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6016:                 '.$default_form_data.'
                   6017:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   6018:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6019:                 <input name="command" value="scantronupload_save" type="hidden" />
1.596.2.12.2.  9(raebur 6020:9):               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6021:9):               '.&Apache::loncommon::start_data_table_header_row().'
                   6022:9):                 <th>
                   6023:9):                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6024:9):                 </th>
                   6025:9):               '.&Apache::loncommon::end_data_table_header_row().'
                   6026:9):               '.&Apache::loncommon::start_data_table_row().'
                   6027:9):             <td>
                   6028:9):                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6029:9):         if ($formatoptions) {
                   6030:9):             $r->print('</td>
                   6031:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6032:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6033:9):                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6034:9):                  </td>
                   6035:9):                  '.&Apache::loncommon::end_data_table_row().'
                   6036:9):                  '.&Apache::loncommon::start_data_table_row().'
                   6037:9):                  <td>'
                   6038:9):             );
                   6039:9):         } else {
                   6040:9):             $r->print(' <br />');
                   6041:9):         }
                   6042:9):         $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6043:9):               </td>
                   6044:9):              '.&Apache::loncommon::end_data_table_row().'
                   6045:9):              '.&Apache::loncommon::end_data_table().'
                   6046:9):              </form>'
                   6047:9):         );
1.596.2.4  raeburn  6048: 
                   6049:     }
                   6050: 
1.422     foxr     6051:     # Chunk of form to prompt for a file to grade and how:
                   6052: 
1.489     albertel 6053:     $result.= '
                   6054:     <br />
                   6055:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6056:     <input type="hidden" name="command" value="scantron_warning" />
                   6057:     '.$default_form_data.'
                   6058:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6059:        '.&Apache::loncommon::start_data_table_header_row().'
                   6060:             <th colspan="2">
1.492     albertel 6061:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6062:             </th>
                   6063:        '.&Apache::loncommon::end_data_table_header_row().'
                   6064:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6065:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6066:        '.&Apache::loncommon::end_data_table_row().'
                   6067:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6068:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6069:        '.&Apache::loncommon::end_data_table_row().'
                   6070:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6071:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6072:        '.&Apache::loncommon::end_data_table_row().'
                   6073:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6074:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6075:        '.&Apache::loncommon::end_data_table_row().'
                   6076:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6077:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6078:        '.&Apache::loncommon::end_data_table_row().'
                   6079:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6080: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6081:             <td>
1.492     albertel 6082: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6083:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6084:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6085: 	    </td>
1.489     albertel 6086:        '.&Apache::loncommon::end_data_table_row().'
                   6087:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6088:             <td colspan="2">
1.572     www      6089:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6090:             </td>
1.489     albertel 6091:        '.&Apache::loncommon::end_data_table_row().'
                   6092:     '.&Apache::loncommon::end_data_table().'
                   6093:     </form>
                   6094: ';
1.162     albertel 6095:    
                   6096:     $r->print($result);
                   6097: 
1.422     foxr     6098:     # Chunk of the form that prompts to view a scoring office file,
                   6099:     # corrected file, skipped records in a file.
                   6100: 
1.489     albertel 6101:     $r->print('
                   6102:    <br />
                   6103:    <form action="/adm/grades" name="scantron_download">
                   6104:      '.$default_form_data.'
                   6105:      <input type="hidden" name="command" value="scantron_download" />
                   6106:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6107:        '.&Apache::loncommon::start_data_table_header_row().'
                   6108:               <th>
1.492     albertel 6109:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6110:               </th>
                   6111:        '.&Apache::loncommon::end_data_table_header_row().'
                   6112:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6113:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6114:                 <br />
1.492     albertel 6115:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6116:        '.&Apache::loncommon::end_data_table_row().'
                   6117:      '.&Apache::loncommon::end_data_table().'
                   6118:    </form>
                   6119:    <br />
                   6120: ');
1.162     albertel 6121: 
1.457     banghart 6122:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6123: 
1.596.2.12.2.  8(raebur 6124:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6125:              $default_form_data."\n".
                   6126:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6127:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6128:              '<th colspan="2">
1.572     www      6129:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6130:              '</th>'."\n".
                   6131:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6132:               &Apache::loncommon::start_data_table_row()."\n".
                   6133:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6134:               '<td> '.$sequence_selector.' </td>'.
                   6135:               &Apache::loncommon::end_data_table_row()."\n".
                   6136:               &Apache::loncommon::start_data_table_row()."\n".
                   6137:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6138:               '<td> '.$file_selector.' </td>'."\n".
                   6139:               &Apache::loncommon::end_data_table_row()."\n".
                   6140:               &Apache::loncommon::start_data_table_row()."\n".
                   6141:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6142:               '<td> '.$format_selector.' </td>'."\n".
                   6143:               &Apache::loncommon::end_data_table_row()."\n".
                   6144:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6145:               '<td> '.&mt('Options').' </td>'."\n".
                   6146:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6147:               &Apache::loncommon::end_data_table_row()."\n".
                   6148:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6149:               '<td colspan="2">'."\n".
                   6150:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6151:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6152:               '</td>'."\n".
                   6153:               &Apache::loncommon::end_data_table_row()."\n".
                   6154:               &Apache::loncommon::end_data_table()."\n".
                   6155:               '</form><br />');
                   6156:     return;
1.75      albertel 6157: }
                   6158: 
1.423     albertel 6159: =pod 
                   6160: 
                   6161: =item username_to_idmap
                   6162: 
1.556     weissno  6163:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6164:     student username:domain.
                   6165: 
                   6166:   Arguments:
                   6167: 
                   6168:     $classlist - reference to the class list hash. This is a hash
                   6169:                  keyed by student name:domain  whose elements are references
1.424     albertel 6170:                  to arrays containing various chunks of information
1.423     albertel 6171:                  about the student. (See loncoursedata for more info).
                   6172: 
                   6173:   Returns
                   6174:     %idmap - the constructed hash
                   6175: 
                   6176: =cut
                   6177: 
1.82      albertel 6178: sub username_to_idmap {
                   6179:     my ($classlist)= @_;
                   6180:     my %idmap;
                   6181:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6182:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6183:5):         unless ($id eq '') {
                   6184:5):             if (!exists($idmap{$id})) {
                   6185:5):                 $idmap{$id} = $student;
                   6186:5):             } else {
                   6187:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6188:5):                 if ($status eq 'Active') {
                   6189:5):                     $idmap{$id} = $student;
                   6190:5):                 }
                   6191:5):             }
                   6192:5):         }
1.82      albertel 6193:     }
                   6194:     return %idmap;
                   6195: }
1.423     albertel 6196: 
                   6197: =pod
                   6198: 
1.424     albertel 6199: =item scantron_fixup_scanline
1.423     albertel 6200: 
                   6201:    Process a requested correction to a scanline.
                   6202: 
                   6203:   Arguments:
1.596.2.12.2.  9(raebur 6204:9):     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6205:     $scan_data         - hash of correction information 
                   6206:                           (see &scantron_getfile())
                   6207:     $line              - existing scanline
                   6208:     $whichline         - line number of the passed in scanline
                   6209:     $field             - type of change to process 
                   6210:                          (either 
1.573     bisitz   6211:                           'ID'     -> correct the student/employee ID
1.423     albertel 6212:                           'CODE'   -> correct the CODE
                   6213:                           'answer' -> fixup the submitted answers)
                   6214:     
                   6215:    $args               - hash of additional info,
                   6216:                           - 'ID' 
                   6217:                                'newid' -> studentID to use in replacement
1.424     albertel 6218:                                           of existing one
1.423     albertel 6219:                           - 'CODE' 
                   6220:                                'CODE_ignore_dup' - set to true if duplicates
                   6221:                                                    should be ignored.
                   6222: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6223:                                         if the existing unfound code should
1.423     albertel 6224:                                         be used as is
                   6225:                           - 'answer'
                   6226:                                'response' - new answer or 'none' if blank
                   6227:                                'question' - the bubble line to change
1.503     raeburn  6228:                                'questionnum' - the question identifier,
                   6229:                                                may include subquestion. 
1.423     albertel 6230: 
                   6231:   Returns:
                   6232:     $line - the modified scanline
                   6233: 
                   6234:   Side effects: 
                   6235:     $scan_data - may be updated
                   6236: 
                   6237: =cut
                   6238: 
1.82      albertel 6239: 
1.157     albertel 6240: sub scantron_fixup_scanline {
                   6241:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6242:     if ($field eq 'ID') {
                   6243: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6244: 	    return ($line,1,'New value too large');
1.157     albertel 6245: 	}
                   6246: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6247: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6248: 				     $args->{'newid'});
                   6249: 	}
                   6250: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6251: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6252: 	if ($args->{'newid'}=~/^\s*$/) {
                   6253: 	    &scan_data($scan_data,"$whichline.user",
                   6254: 		       $args->{'username'}.':'.$args->{'domain'});
                   6255: 	}
1.186     albertel 6256:     } elsif ($field eq 'CODE') {
1.192     albertel 6257: 	if ($args->{'CODE_ignore_dup'}) {
                   6258: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6259: 	}
                   6260: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6261: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6262: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6263: 		return ($line,1,'New CODE value too large');
                   6264: 	    }
                   6265: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6266: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6267: 	    }
                   6268: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6269: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6270: 	}
1.157     albertel 6271:     } elsif ($field eq 'answer') {
1.497     foxr     6272: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6273: 	my $off=$scantron_config->{'Qoff'};
                   6274: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6275: 	my $answer=${off}x$length;
                   6276: 	if ($args->{'response'} eq 'none') {
                   6277: 	    &scan_data($scan_data,
1.503     raeburn  6278: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6279: 	} else {
                   6280: 	    if ($on eq 'letter') {
                   6281: 		my @alphabet=('A'..'Z');
                   6282: 		$answer=$alphabet[$args->{'response'}];
                   6283: 	    } elsif ($on eq 'number') {
                   6284: 		$answer=$args->{'response'}+1;
                   6285: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6286: 	    } else {
1.497     foxr     6287: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6288: 	    }
1.497     foxr     6289: 	    &scan_data($scan_data,
1.503     raeburn  6290: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6291: 	}
1.497     foxr     6292: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6293: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6294:     }
                   6295:     return $line;
                   6296: }
1.423     albertel 6297: 
                   6298: =pod
                   6299: 
                   6300: =item scan_data
                   6301: 
                   6302:     Edit or look up  an item in the scan_data hash.
                   6303: 
                   6304:   Arguments:
                   6305:     $scan_data  - The hash (see scantron_getfile)
                   6306:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6307:                   scantronfilename_key).
1.423     albertel 6308:     $data        - New value of the hash entry.
                   6309:     $delete      - If true, the entry is removed from the hash.
                   6310: 
                   6311:   Returns:
                   6312:     The new value of the hash table field (undefined if deleted).
                   6313: 
                   6314: =cut
                   6315: 
                   6316: 
1.157     albertel 6317: sub scan_data {
                   6318:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6319:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6320:     if (defined($value)) {
                   6321: 	$scan_data->{$filename.'_'.$key} = $value;
                   6322:     }
                   6323:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6324:     return $scan_data->{$filename.'_'.$key};
                   6325: }
1.423     albertel 6326: 
1.495     albertel 6327: # ----- These first few routines are general use routines.----
                   6328: 
                   6329: # Return the number of occurences of a pattern in a string.
                   6330: 
                   6331: sub occurence_count {
                   6332:     my ($string, $pattern) = @_;
                   6333: 
                   6334:     my @matches = ($string =~ /$pattern/g);
                   6335: 
                   6336:     return scalar(@matches);
                   6337: }
                   6338: 
                   6339: 
                   6340: # Take a string known to have digits and convert all the
                   6341: # digits into letters in the range J,A..I.
                   6342: 
                   6343: sub digits_to_letters {
                   6344:     my ($input) = @_;
                   6345: 
                   6346:     my @alphabet = ('J', 'A'..'I');
                   6347: 
                   6348:     my @input    = split(//, $input);
                   6349:     my $output ='';
                   6350:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6351: 	if ($input[$i] =~ /\d/) {
                   6352: 	    $output .= $alphabet[$input[$i]];
                   6353: 	} else {
                   6354: 	    $output .= $input[$i];
                   6355: 	}
                   6356:     }
                   6357:     return $output;
                   6358: }
                   6359: 
1.423     albertel 6360: =pod 
                   6361: 
                   6362: =item scantron_parse_scanline
                   6363: 
                   6364:   Decodes a scanline from the selected scantron file
                   6365: 
                   6366:  Arguments:
                   6367:     line             - The text of the scantron file line to process
                   6368:     whichline        - Line number
                   6369:     scantron_config  - Hash describing the format of the scantron lines.
                   6370:     scan_data        - Hash of extra information about the scanline
                   6371:                        (see scantron_getfile for more information)
                   6372:     just_header      - True if should not process question answers but only
                   6373:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6374:3):     randomorder      - True if randomorder in use
                   6375:3):     randompick       - True if randompick in use
                   6376:3):     sequence         - Exam folder URL
                   6377:3):     master_seq       - Ref to array containing symbs in exam folder
                   6378:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6379:3):                        (corresponding values are resource objects)
                   6380:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6381:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6382:3):                        are refs to an array of resource objects, ordered
                   6383:3):                        according to order used for CODE, when randomorder
                   6384:3):                        and or randompick are in use.
                   6385:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6386:3):                        for current line to question number used for same question
                   6387:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6388:3):     startline        - Ref to hash where key is question number (0 is first)
                   6389:3):                        and value is number of first bubble line for current 
                   6390:3):                        student or code-based randompick and/or randomorder.
                   6391:3):     totalref         - Ref of scalar used to score total number of bubble
                   6392:3):                        lines needed for responses in a scan line (used when
                   6393:3):                        randompick in use. 
                   6394:3): 
1.423     albertel 6395:  Returns:
                   6396:    Hash containing the result of parsing the scanline
                   6397: 
                   6398:    Keys are all proceeded by the string 'scantron.'
                   6399: 
                   6400:        CODE    - the CODE in use for this scanline
                   6401:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6402:                  by the operator
                   6403:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6404:                             CODEs were selected, but the usage has been
                   6405:                             forced by the operator
1.556     weissno  6406:        ID  - student/employee ID
1.423     albertel 6407:        PaperID - if used, the ID number printed on the sheet when the 
                   6408:                  paper was scanned
                   6409:        FirstName - first name from the sheet
                   6410:        LastName  - last name from the sheet
                   6411: 
                   6412:      if just_header was not true these key may also exist
                   6413: 
1.447     foxr     6414:        missingerror - a list of bubble ranges that are considered to be answers
                   6415:                       to a single question that don't have any bubbles filled in.
                   6416:                       Of the form questionnumber:firstbubblenumber:count.
                   6417:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6418:                       to a single question that have more than one bubble filled in.
                   6419:                       Of the form questionnumber::firstbubblenumber:count
                   6420:    
                   6421:                 In the above, count is the number of bubble responses in the
                   6422:                 input line needed to represent the possible answers to the question.
                   6423:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6424:                 per line would have count = 2.
                   6425: 
1.423     albertel 6426:        maxquest     - the number of the last bubble line that was parsed
                   6427: 
                   6428:        (<number> starts at 1)
                   6429:        <number>.answer - zero or more letters representing the selected
                   6430:                          letters from the scanline for the bubble line 
                   6431:                          <number>.
                   6432:                          if blank there was either no bubble or there where
                   6433:                          multiple bubbles, (consult the keys missingerror and
                   6434:                          doubleerror if this is an error condition)
                   6435: 
                   6436: =cut
                   6437: 
1.82      albertel 6438: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6439:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6440:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6441:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6442: 
1.82      albertel 6443:     my %record;
1.596.2.12.2.  6(raebur 6444:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6445:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6446: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6447: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6448: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6449: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6450: 	    $record{'scantron.CODE'}=substr($data,
                   6451: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6452: 					    $$scantron_config{'CODElength'});
1.191     albertel 6453: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6454: 		$record{'scantron.useCODE'}=1;
                   6455: 	    }
1.192     albertel 6456: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6457: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6458: 	    }
1.82      albertel 6459: 	} else {
                   6460: 	    #FIXME interpret first N questions
                   6461: 	}
                   6462:     }
1.83      albertel 6463:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6464: 				  $$scantron_config{'IDlength'});
1.157     albertel 6465:     $record{'scantron.PaperID'}=
                   6466: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6467: 	       $$scantron_config{'PaperIDlength'});
                   6468:     $record{'scantron.FirstName'}=
                   6469: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6470: 	       $$scantron_config{'FirstNamelength'});
                   6471:     $record{'scantron.LastName'}=
                   6472: 	substr($data,$$scantron_config{'LastName'}-1,
                   6473: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6474:     if ($just_header) { return \%record; }
1.194     albertel 6475: 
1.82      albertel 6476:     my @alphabet=('A'..'Z');
                   6477:     my $questnum=0;
1.447     foxr     6478:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6479: 
1.596.2.12.2.  6(raebur 6480:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6481:3):     if ($randompick || $randomorder) {
                   6482:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6483:3):                                          $master_seq,$symb_to_resource,
                   6484:3):                                          $partids_by_symb,$orderedforcode,
                   6485:3):                                          $respnumlookup,$startline);
                   6486:3):         if ($total) {
                   6487:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6488:3):         }
                   6489:3):         if (ref($totalref)) {
                   6490:3):             $$totalref = $total;
                   6491:3):         }
                   6492:3):     }
                   6493:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6494:     chomp($questions);		# Get rid of any trailing \n.
                   6495:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6496:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6497:3):         my $answers_needed;
                   6498:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6499:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6500:3):         } else {
                   6501:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6502:3):         }
1.503     raeburn  6503:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6504:                              || 1;
                   6505:         $questnum++;
                   6506:         my $quest_id = $questnum;
                   6507:         my $currentquest = substr($questions,0,$answer_length);
                   6508:         $questions       = substr($questions,$answer_length);
                   6509:         if (length($currentquest) < $answer_length) { next; }
                   6510: 
1.596.2.12.2.  6(raebur 6511:3):         my $subdivided;
                   6512:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6513:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6514:3):         } else {
                   6515:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6516:3):         }
                   6517:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6518:             my $subquestnum = 1;
                   6519:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6520:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6521:             foreach my $subans (@subanswers_needed) {
                   6522:                 my $subans_length =
                   6523:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6524:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6525:                 $subquestions   = substr($subquestions,$subans_length);
                   6526:                 $quest_id = "$questnum.$subquestnum";
                   6527:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6528:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6529:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6530:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6531:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6532:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6533:                 } else {
                   6534:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6535:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6536:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6537:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6538:                 }
                   6539:                 $subquestnum ++;
                   6540:             }
                   6541:         } else {
                   6542:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6543:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6544:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6545:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6546:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6547:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6548:             } else {
                   6549:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6550:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6551:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6552:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6553:             }
                   6554:         }
                   6555:     }
                   6556:     $record{'scantron.maxquest'}=$questnum;
                   6557:     return \%record;
                   6558: }
1.447     foxr     6559: 
1.596.2.12.2.  6(raebur 6560:3): sub get_master_seq {
                   6561:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6562:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6563:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6564:3):     my $resource_error;
                   6565:3):     foreach my $resource (@{$resources}) {
                   6566:3):         my $ressymb;
                   6567:3):         if (ref($resource)) {
                   6568:3):             $ressymb = $resource->symb();
                   6569:3):             push(@{$master_seq},$ressymb);
                   6570:3):             $symb_to_resource->{$ressymb} = $resource;
                   6571:3):         } else {
                   6572:3):             $resource_error = 1;
                   6573:3):             last;
                   6574:3):         }
                   6575:3):     }
                   6576:3):     return $resource_error;
                   6577:3): }
                   6578:3): 
                   6579:3): sub get_respnum_lookups {
                   6580:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6581:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6582:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6583:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6584:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6585:3):                    (ref($startline) eq 'HASH'));
                   6586:3):     my ($user,$scancode);
                   6587:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6588:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6589:3):         $scancode = $record->{'scantron.CODE'};
                   6590:3):     } else {
                   6591:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6592:3):     }
                   6593:3):     my @mapresources =
                   6594:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6595:3):                      $orderedforcode);
                   6596:3):     my $total = 0;
                   6597:3):     my $count = 0;
                   6598:3):     foreach my $resource (@mapresources) {
                   6599:3):         my $id = $resource->id();
                   6600:3):         my $symb = $resource->symb();
                   6601:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6602:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6603:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6604:3):                 if ($respnum ne '') {
                   6605:3):                     $respnumlookup->{$count} = $respnum;
                   6606:3):                     $startline->{$count} = $total;
                   6607:3):                     $total += $bubble_lines_per_response{$respnum};
                   6608:3):                     $count ++;
                   6609:3):                 }
                   6610:3):             }
                   6611:3):         }
                   6612:3):     }
                   6613:3):     return $total;
                   6614:3): }
                   6615:3): 
1.503     raeburn  6616: sub scantron_validator_lettnum {
                   6617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6618:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6619:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6620: 
                   6621:     # Qon 'letter' implies for each slot in currquest we have:
                   6622:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6623:     #    about anything else (esp. a value of Qoff) for missing
                   6624:     #    bubbles.
                   6625:     #
                   6626:     # Qon 'number' implies each slot gives a digit that indexes the
                   6627:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6628:     #    and * or ? for double bubbles on a single line.
                   6629:     #
1.447     foxr     6630: 
1.503     raeburn  6631:     my $matchon;
                   6632:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6633:         $matchon = '[A-Z]';
                   6634:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6635:         $matchon = '\d';
                   6636:     }
                   6637:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6638:3):     my $responsenum = $questnum-1;
                   6639:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6640:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6641:3):     }
                   6642:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6643:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6644:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6645:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6646:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6647:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6648:         my @singlelines = split('',$currquest);
                   6649:         foreach my $entry (@singlelines) {
                   6650:             $occurrences = &occurence_count($entry,$matchon);
                   6651:             if ($occurrences > 1) {
                   6652:                 last;
                   6653:             }
1.596.2.12.2.  6(raebur 6654:3):         }
1.503     raeburn  6655:     } else {
                   6656:         $occurrences = &occurence_count($currquest,$matchon); 
                   6657:     }
                   6658:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6659:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6660:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6661:             my $bubble = substr($currquest,$ans,1);
                   6662:             if ($bubble =~ /$matchon/ ) {
                   6663:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6664:                     if ($bubble == 0) {
                   6665:                         $bubble = 10; 
                   6666:                     }
                   6667:                     $record->{"scantron.$ansnum.answer"} = 
                   6668:                         $alphabet->[$bubble-1];
                   6669:                 } else {
                   6670:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6671:                 }
                   6672:             } else {
                   6673:                 $record->{"scantron.$ansnum.answer"}='';
                   6674:             }
                   6675:             $ansnum++;
                   6676:         }
                   6677:     } elsif (!defined($currquest)
                   6678:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6679:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6680:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6681:             $record->{"scantron.$ansnum.answer"}='';
                   6682:             $ansnum++;
                   6683:         }
                   6684:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6685:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6686:         }
                   6687:     } else {
                   6688:         if ($$scantron_config{'Qon'} eq 'number') {
                   6689:             $currquest = &digits_to_letters($currquest);            
                   6690:         }
                   6691:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6692:             my $bubble = substr($currquest,$ans,1);
                   6693:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6694:             $ansnum++;
                   6695:         }
                   6696:     }
                   6697:     return $ansnum;
                   6698: }
1.447     foxr     6699: 
1.503     raeburn  6700: sub scantron_validator_positional {
                   6701:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6702:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6703:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6704: 
1.503     raeburn  6705:     # Otherwise there's a positional notation;
                   6706:     # each bubble line requires Qlength items, and there are filled in
                   6707:     # bubbles for each case where there 'Qon' characters.
                   6708:     #
1.447     foxr     6709: 
1.503     raeburn  6710:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6711: 
1.503     raeburn  6712:     # If the split only gives us one element.. the full length of the
                   6713:     # answer string, no bubbles are filled in:
1.447     foxr     6714: 
1.507     raeburn  6715:     if ($answers_needed eq '') {
                   6716:         return;
                   6717:     }
                   6718: 
1.503     raeburn  6719:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6720:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6721:             $record->{"scantron.$ansnum.answer"}='';
                   6722:             $ansnum++;
                   6723:         }
                   6724:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6725:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6726:         }
                   6727:     } elsif (scalar(@array) == 2) {
                   6728:         my $location = length($array[0]);
                   6729:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6730:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6731:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6732:             if ($ans eq $line_num) {
                   6733:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6734:             } else {
                   6735:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6736:             }
                   6737:             $ansnum++;
                   6738:          }
                   6739:     } else {
                   6740:         #  If there's more than one instance of a bubble character
                   6741:         #  That's a double bubble; with positional notation we can
                   6742:         #  record all the bubbles filled in as well as the
                   6743:         #  fact this response consists of multiple bubbles.
                   6744:         #
1.596.2.12.2.  6(raebur 6745:3):         my $responsenum = $questnum-1;
                   6746:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6747:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6748:3):         }
                   6749:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6750:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6751:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6752:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6753:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6754:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6755:             my $doubleerror = 0;
                   6756:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6757:                    (!$doubleerror)) {
                   6758:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6759:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6760:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6761:                if (length(@currarray) > 2) {
                   6762:                    $doubleerror = 1;
                   6763:                } 
                   6764:             }
                   6765:             if ($doubleerror) {
                   6766:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6767:             }
                   6768:         } else {
                   6769:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6770:         }
                   6771:         my $item = $ansnum;
                   6772:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6773:             $record->{"scantron.$item.answer"} = '';
                   6774:             $item ++;
                   6775:         }
1.447     foxr     6776: 
1.503     raeburn  6777:         my @ans=@array;
                   6778:         my $i=0;
                   6779:         my $increment = 0;
                   6780:         while ($#ans) {
                   6781:             $i+=length($ans[0]) + $increment;
                   6782:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6783:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6784:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6785:             shift(@ans);
                   6786:             $increment = 1;
                   6787:         }
                   6788:         $ansnum += $answers_needed;
1.82      albertel 6789:     }
1.503     raeburn  6790:     return $ansnum;
1.82      albertel 6791: }
                   6792: 
1.423     albertel 6793: =pod
                   6794: 
                   6795: =item scantron_add_delay
                   6796: 
                   6797:    Adds an error message that occurred during the grading phase to a
                   6798:    queue of messages to be shown after grading pass is complete
                   6799: 
                   6800:  Arguments:
1.424     albertel 6801:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6802:    $scanline    - the scanline that caused the error
                   6803:    $errormesage - the error message
                   6804:    $errorcode   - a numeric code for the error
                   6805: 
                   6806:  Side Effects:
1.424     albertel 6807:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6808: 
                   6809: =cut
                   6810: 
1.82      albertel 6811: sub scantron_add_delay {
1.140     albertel 6812:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6813:     push(@$delayqueue,
                   6814: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6815: 	  'ecode' => $errorcode }
                   6816: 	 );
1.82      albertel 6817: }
                   6818: 
1.423     albertel 6819: =pod
                   6820: 
                   6821: =item scantron_find_student
                   6822: 
1.424     albertel 6823:    Finds the username for the current scanline
                   6824: 
                   6825:   Arguments:
                   6826:    $scantron_record - hash result from scantron_parse_scanline
                   6827:    $scan_data       - hash of correction information 
                   6828:                       (see &scantron_getfile() form more information)
                   6829:    $idmap           - hash from &username_to_idmap()
                   6830:    $line            - number of current scanline
                   6831:  
                   6832:   Returns:
                   6833:    Either 'username:domain' or undef if unknown
                   6834: 
1.423     albertel 6835: =cut
                   6836: 
1.82      albertel 6837: sub scantron_find_student {
1.157     albertel 6838:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6839:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6840:     if ($scanID =~ /^\s*$/) {
                   6841:  	return &scan_data($scan_data,"$line.user");
                   6842:     }
1.83      albertel 6843:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6844:  	if (lc($id) eq lc($scanID)) {
                   6845:  	    return $$idmap{$id};
                   6846:  	}
1.83      albertel 6847:     }
                   6848:     return undef;
                   6849: }
                   6850: 
1.423     albertel 6851: =pod
                   6852: 
                   6853: =item scantron_filter
                   6854: 
1.424     albertel 6855:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6856:    hidden resources was selected
                   6857: 
1.423     albertel 6858: =cut
                   6859: 
1.83      albertel 6860: sub scantron_filter {
                   6861:     my ($curres)=@_;
1.331     albertel 6862: 
                   6863:     if (ref($curres) && $curres->is_problem()) {
                   6864: 	# if the user has asked to not have either hidden
                   6865: 	# or 'randomout' controlled resources to be graded
                   6866: 	# don't include them
                   6867: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6868: 	    && $curres->randomout) {
                   6869: 	    return 0;
                   6870: 	}
1.83      albertel 6871: 	return 1;
                   6872:     }
                   6873:     return 0;
1.82      albertel 6874: }
                   6875: 
1.423     albertel 6876: =pod
                   6877: 
                   6878: =item scantron_process_corrections
                   6879: 
1.424     albertel 6880:    Gets correction information out of submitted form data and corrects
                   6881:    the scanline
                   6882: 
1.423     albertel 6883: =cut
                   6884: 
1.157     albertel 6885: sub scantron_process_corrections {
                   6886:     my ($r) = @_;
1.596.2.12.2.  9(raebur 6887:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6888:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6889:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6890:     my $which=$env{'form.scantron_line'};
1.200     albertel 6891:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6892:     my ($skip,$err,$errmsg);
1.257     albertel 6893:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6894: 	$skip=1;
1.257     albertel 6895:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6896: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6897: 	    $env{'form.scantron_domain'};
1.157     albertel 6898: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6899: 	($line,$err,$errmsg)=
                   6900: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6901: 				     'ID',{'newid'=>$newid,
1.257     albertel 6902: 				    'username'=>$env{'form.scantron_username'},
                   6903: 				    'domain'=>$env{'form.scantron_domain'}});
                   6904:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6905: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6906: 	my $newCODE;
1.192     albertel 6907: 	my %args;
1.190     albertel 6908: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6909: 	    $newCODE='use_unfound';
1.190     albertel 6910: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6911: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6912: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6913: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6914: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6915: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6916: 	}
1.257     albertel 6917: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6918: 	    $args{'CODE_ignore_dup'}=1;
                   6919: 	}
                   6920: 	$args{'CODE'}=$newCODE;
1.186     albertel 6921: 	($line,$err,$errmsg)=
                   6922: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6923: 				     'CODE',\%args);
1.257     albertel 6924:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6925: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6926: 	    ($line,$err,$errmsg)=
                   6927: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6928: 					 $which,'answer',
                   6929: 					 { 'question'=>$question,
1.503     raeburn  6930: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6931:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6932: 	    if ($err) { last; }
                   6933: 	}
                   6934:     }
                   6935:     if ($err) {
1.596.2.12.2.  0(raebur 6936:3): 	$r->print(
                   6937:3):             '<p class="LC_error">'
                   6938:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6939:3):                 $errmsg)
          1(raebur 6940:3):            .'</p>');
1.157     albertel 6941:     } else {
1.200     albertel 6942: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6943: 	&scantron_putfile($scanlines,$scan_data);
                   6944:     }
                   6945: }
                   6946: 
1.423     albertel 6947: =pod
                   6948: 
                   6949: =item reset_skipping_status
                   6950: 
1.424     albertel 6951:    Forgets the current set of remember skipped scanlines (and thus
                   6952:    reverts back to considering all lines in the
                   6953:    scantron_skipped_<filename> file)
                   6954: 
1.423     albertel 6955: =cut
                   6956: 
1.200     albertel 6957: sub reset_skipping_status {
                   6958:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6959:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6960:     &scantron_putfile(undef,$scan_data);
                   6961: }
                   6962: 
1.423     albertel 6963: =pod
                   6964: 
                   6965: =item start_skipping
                   6966: 
1.424     albertel 6967:    Marks a scanline to be skipped. 
                   6968: 
1.423     albertel 6969: =cut
                   6970: 
1.376     albertel 6971: sub start_skipping {
1.200     albertel 6972:     my ($scan_data,$i)=@_;
                   6973:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6974:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6975: 	$remembered{$i}=2;
                   6976:     } else {
                   6977: 	$remembered{$i}=1;
                   6978:     }
1.200     albertel 6979:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6980: }
                   6981: 
1.423     albertel 6982: =pod
                   6983: 
                   6984: =item should_be_skipped
                   6985: 
1.424     albertel 6986:    Checks whether a scanline should be skipped.
                   6987: 
1.423     albertel 6988: =cut
                   6989: 
1.200     albertel 6990: sub should_be_skipped {
1.376     albertel 6991:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6992:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6993: 	# not redoing old skips
1.376     albertel 6994: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6995: 	return 0;
                   6996:     }
                   6997:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6998: 
                   6999:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7000: 	return 0;
                   7001:     }
1.200     albertel 7002:     return 1;
                   7003: }
                   7004: 
1.423     albertel 7005: =pod
                   7006: 
                   7007: =item remember_current_skipped
                   7008: 
1.424     albertel 7009:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7010:    file and remembers them into scan_data for later use.
                   7011: 
1.423     albertel 7012: =cut
                   7013: 
1.200     albertel 7014: sub remember_current_skipped {
                   7015:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7016:     my %to_remember;
                   7017:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7018: 	if ($scanlines->{'skipped'}[$i]) {
                   7019: 	    $to_remember{$i}=1;
                   7020: 	}
                   7021:     }
1.376     albertel 7022: 
1.200     albertel 7023:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7024:     &scantron_putfile(undef,$scan_data);
                   7025: }
                   7026: 
1.423     albertel 7027: =pod
                   7028: 
                   7029: =item check_for_error
                   7030: 
1.424     albertel 7031:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  7032:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7033:     something went wrong.
                   7034: 
1.423     albertel 7035: =cut
                   7036: 
1.200     albertel 7037: sub check_for_error {
                   7038:     my ($r,$result)=@_;
                   7039:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7040: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7041:     }
                   7042: }
1.157     albertel 7043: 
1.423     albertel 7044: =pod
                   7045: 
                   7046: =item scantron_warning_screen
                   7047: 
1.424     albertel 7048:    Interstitial screen to make sure the operator has selected the
                   7049:    correct options before we start the validation phase.
                   7050: 
1.423     albertel 7051: =cut
                   7052: 
1.203     albertel 7053: sub scantron_warning_screen {
1.596.2.12.2.  1(raebur 7054:0):     my ($button_text,$symb)=@_;
1.257     albertel 7055:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.596.2.12.2.  9(raebur 7056:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7057:     my $CODElist;
1.284     albertel 7058:     if ($scantron_config{'CODElocation'} &&
                   7059: 	$scantron_config{'CODEstart'} &&
                   7060: 	$scantron_config{'CODElength'}) {
                   7061: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7062:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7063: 	$CODElist=
1.492     albertel 7064: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7065: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7066:     }
1.596.2.12.2.  (raeburn 7067:):     my $lastbubblepoints;
                   7068:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7069:):         $lastbubblepoints =
                   7070:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7071:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7072:):     }
1.492     albertel 7073:     return ('
1.203     albertel 7074: <p>
1.492     albertel 7075: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7076:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7077: </p>
                   7078: <table>
1.492     albertel 7079: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7080: <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 7081:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7082: </table>
1.596.2.12.2.  1(raebur 7083:0): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
                   7084: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 7085: 
                   7086: <br />
1.492     albertel 7087: ');
1.203     albertel 7088: }
                   7089: 
1.423     albertel 7090: =pod
                   7091: 
                   7092: =item scantron_do_warning
                   7093: 
1.424     albertel 7094:    Check if the operator has picked something for all required
                   7095:    fields. Error out if something is missing.
                   7096: 
1.423     albertel 7097: =cut
                   7098: 
1.203     albertel 7099: sub scantron_do_warning {
1.596.2.12.2.  1(raebur 7100:0):     my ($r,$symb)=@_;
1.203     albertel 7101:     if (!$symb) {return '';}
1.324     albertel 7102:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7103:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7104:     if ( $env{'form.selectpage'} eq '' ||
                   7105: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7106: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7107: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7108: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7109: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7110: 	} 
1.257     albertel 7111: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7112: 	    $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 7113: 	} 
1.257     albertel 7114: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7115: 	    $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 7116: 	} 
                   7117:     } else {
1.596.2.12.2.  1(raebur 7118:0): 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
          (raeburn 7119:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7120: 	$r->print('
1.596.2.12.2.  (raeburn 7121:): '.$warning.$bubbledbyhand.'
1.492     albertel 7122: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7123: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7124: ');
1.237     albertel 7125:     }
1.596.2.12.2.  1(raebur 7126:0):     $r->print("</form><br />");
1.203     albertel 7127:     return '';
                   7128: }
                   7129: 
1.423     albertel 7130: =pod
                   7131: 
                   7132: =item scantron_form_start
                   7133: 
1.424     albertel 7134:     html hidden input for remembering all selected grading options
                   7135: 
1.423     albertel 7136: =cut
                   7137: 
1.203     albertel 7138: sub scantron_form_start {
                   7139:     my ($max_bubble)=@_;
                   7140:     my $result= <<SCANTRONFORM;
                   7141: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7142:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7143:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7144:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7145:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7146:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7147:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7148:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7149:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7150:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7151: SCANTRONFORM
1.447     foxr     7152: 
                   7153:   my $line = 0;
                   7154:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7155:        my $chunk =
                   7156: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7157:        $chunk .=
                   7158: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7159:        $chunk .= 
                   7160:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7161:        $chunk .=
                   7162:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7163:3):        $chunk .=
                   7164:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7165:        $result .= $chunk;
                   7166:        $line++;
1.596.2.12.2.  6(raebur 7167:3):     }
1.203     albertel 7168:     return $result;
                   7169: }
                   7170: 
1.423     albertel 7171: =pod
                   7172: 
                   7173: =item scantron_validate_file
                   7174: 
1.596.2.6  raeburn  7175:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7176: 
                   7177:     Also processes any necessary information resets that need to
                   7178:     occur before validation begins (ignore previous corrections,
                   7179:     restarting the skipped records processing)
                   7180: 
1.423     albertel 7181: =cut
                   7182: 
1.157     albertel 7183: sub scantron_validate_file {
1.596.2.12.2.  1(raebur 7184:0):     my ($r,$symb) = @_;
1.157     albertel 7185:     if (!$symb) {return '';}
1.324     albertel 7186:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7187:     
1.596.2.12.2.  0(raebur 7188:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7189:     # them when doing the corrections reset
1.257     albertel 7190:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7191: 	&reset_skipping_status();
                   7192:     }
1.257     albertel 7193:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7194: 	&remember_current_skipped();
1.257     albertel 7195: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7196:     }
                   7197: 
1.257     albertel 7198:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7199: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7200: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7201: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7202: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7203:     }
1.200     albertel 7204: 
1.257     albertel 7205:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7206: 	&scantron_process_corrections($r);
                   7207:     }
1.503     raeburn  7208:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7209:     #get the student pick code ready
                   7210:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7211:     my $nav_error;
1.596.2.12.2.  9(raebur 7212:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 7213:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7214:     if ($nav_error) {
                   7215:         $r->print(&navmap_errormsg());
                   7216:         return '';
                   7217:     }
1.203     albertel 7218:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7219:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7220:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7221:):     }
1.157     albertel 7222:     $r->print($result);
                   7223:     
1.334     albertel 7224:     my @validate_phases=( 'sequence',
                   7225: 			  'ID',
1.157     albertel 7226: 			  'CODE',
                   7227: 			  'doublebubble',
                   7228: 			  'missingbubbles');
1.257     albertel 7229:     if (!$env{'form.validatepass'}) {
                   7230: 	$env{'form.validatepass'} = 0;
1.157     albertel 7231:     }
1.257     albertel 7232:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7233: 
1.448     foxr     7234: 
1.157     albertel 7235:     my $stop=0;
                   7236:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7237: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7238: 	$r->rflush();
1.596.2.12.2.  6(raebur 7239:3): 
1.157     albertel 7240: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7241: 	{
                   7242: 	    no strict 'refs';
                   7243: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7244: 	}
                   7245:     }
                   7246:     if (!$stop) {
1.596.2.12.2.  1(raebur 7247:0): 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7248: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7249:                   $warning.
                   7250:                   &mt('Perform verification for each student after storage of submissions?').
                   7251:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7252:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7253:                   ('&nbsp;'x3).'<label>'.
                   7254:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7255:                   '</label></span><br />'.
                   7256:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.596.2.12.2.  1(raebur 7257:0):                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7258:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7259:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7260:     } else {
                   7261: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7262: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7263:     }
                   7264:     if ($stop) {
1.334     albertel 7265: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7266: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7267: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7268: 
1.596.2.12.2.  1(raebur 7269: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 7270: 	} else {
1.503     raeburn  7271:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7272: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7273:             } else {
1.539     riegler  7274:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7275:             }
1.492     albertel 7276: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7277: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7278: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7279: 	}
1.157     albertel 7280:     }
1.596.2.12.2.  1(raebur 7281:0):     $r->print(" </form><br />");
1.157     albertel 7282:     return '';
                   7283: }
                   7284: 
1.423     albertel 7285: 
                   7286: =pod
                   7287: 
                   7288: =item scantron_remove_file
                   7289: 
1.596.2.6  raeburn  7290:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7291:    scantron_original_<filename> is never removed
                   7292: 
                   7293: 
1.423     albertel 7294: =cut
                   7295: 
1.200     albertel 7296: sub scantron_remove_file {
1.192     albertel 7297:     my ($which)=@_;
1.257     albertel 7298:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7299:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7300:     my $file='scantron_';
1.200     albertel 7301:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7302: 	$file.=$which.'_';
1.192     albertel 7303:     } else {
                   7304: 	return 'refused';
                   7305:     }
1.257     albertel 7306:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7307:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7308: }
                   7309: 
1.423     albertel 7310: 
                   7311: =pod
                   7312: 
                   7313: =item scantron_remove_scan_data
                   7314: 
1.596.2.6  raeburn  7315:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7316:    data file.  (In the case that both the are doing skipped records we need
                   7317:    to remember the old skipped lines for the time being so that element
                   7318:    persists for a while.)
                   7319: 
1.423     albertel 7320: =cut
                   7321: 
1.200     albertel 7322: sub scantron_remove_scan_data {
1.257     albertel 7323:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7324:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7325:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7326:     my @todelete;
1.257     albertel 7327:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7328:     foreach my $key (@keys) {
                   7329: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7330: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7331: 		$key=~/remember_skipping/) {
                   7332: 		next;
                   7333: 	    }
1.192     albertel 7334: 	    push(@todelete,$key);
                   7335: 	}
                   7336:     }
1.200     albertel 7337:     my $result;
1.192     albertel 7338:     if (@todelete) {
1.491     albertel 7339: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7340: 				       \@todelete,$cdom,$cname);
                   7341:     } else {
                   7342: 	$result = 'ok';
1.192     albertel 7343:     }
                   7344:     return $result;
                   7345: }
                   7346: 
1.423     albertel 7347: 
                   7348: =pod
                   7349: 
                   7350: =item scantron_getfile
                   7351: 
1.596.2.6  raeburn  7352:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7353:     the scan_data hash
                   7354:   
                   7355:   Arguments:
                   7356:     None
                   7357: 
                   7358:   Returns:
                   7359:     2 hash references
                   7360: 
                   7361:      - first one has 
                   7362:          orig      -
                   7363:          corrected -
                   7364:          skipped   -  each of which points to an array ref of the specified
                   7365:                       file broken up into individual lines
                   7366:          count     - number of scanlines
                   7367:  
                   7368:      - second is the scan_data hash possible keys are
1.425     albertel 7369:        ($number refers to scanline numbered $number and thus the key affects
                   7370:         only that scanline
                   7371:         $bubline refers to the specific bubble line element and the aspects
                   7372:         refers to that specific bubble line element)
                   7373: 
                   7374:        $number.user - username:domain to use
                   7375:        $number.CODE_ignore_dup 
                   7376:                     - ignore the duplicate CODE error 
                   7377:        $number.useCODE
                   7378:                     - use the CODE in the scanline as is
                   7379:        $number.no_bubble.$bubline
                   7380:                     - it is valid that there is no bubbled in bubble
                   7381:                       at $number $bubline
                   7382:        remember_skipping
                   7383:                     - a frozen hash containing keys of $number and values
                   7384:                       of either 
                   7385:                         1 - we are on a 'do skipped records pass' and plan
                   7386:                             on processing this line
                   7387:                         2 - we are on a 'do skipped records pass' and this
                   7388:                             scanline has been marked to skip yet again
1.424     albertel 7389: 
1.423     albertel 7390: =cut
                   7391: 
1.157     albertel 7392: sub scantron_getfile {
1.200     albertel 7393:     #FIXME really would prefer a scantron directory
1.257     albertel 7394:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7396:     my $lines;
                   7397:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7398: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7399:     my %scanlines;
                   7400:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7401:     my $temp=$scanlines{'orig'};
                   7402:     $scanlines{'count'}=$#$temp;
                   7403: 
                   7404:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7405: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7406:     if ($lines eq '-1') {
                   7407: 	$scanlines{'corrected'}=[];
                   7408:     } else {
                   7409: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7410:     }
                   7411:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7412: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7413:     if ($lines eq '-1') {
                   7414: 	$scanlines{'skipped'}=[];
                   7415:     } else {
                   7416: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7417:     }
1.175     albertel 7418:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7419:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7420:     my %scan_data = @tmp;
                   7421:     return (\%scanlines,\%scan_data);
                   7422: }
                   7423: 
1.423     albertel 7424: =pod
                   7425: 
                   7426: =item lonnet_putfile
                   7427: 
1.424     albertel 7428:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7429: 
                   7430:  Arguments:
                   7431:    $contents - data to store
                   7432:    $filename - filename to store $contents into
                   7433: 
                   7434:  Returns:
                   7435:    result value from &Apache::lonnet::finishuserfileupload
                   7436: 
1.423     albertel 7437: =cut
                   7438: 
1.157     albertel 7439: sub lonnet_putfile {
                   7440:     my ($contents,$filename)=@_;
1.257     albertel 7441:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7442:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7443:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7444:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7445: 
                   7446: }
                   7447: 
1.423     albertel 7448: =pod
                   7449: 
                   7450: =item scantron_putfile
                   7451: 
1.596.2.6  raeburn  7452:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7453:     scan_data hash. (Does not modify the original version only the
                   7454:     corrected and skipped versions.
                   7455: 
                   7456:  Arguments:
                   7457:     $scanlines - hash ref that looks like the first return value from
                   7458:                  &scantron_getfile()
                   7459:     $scan_data - hash ref that looks like the second return value from
                   7460:                  &scantron_getfile()
                   7461: 
1.423     albertel 7462: =cut
                   7463: 
1.157     albertel 7464: sub scantron_putfile {
                   7465:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7466:     #FIXME really would prefer a scantron directory
1.257     albertel 7467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7469:     if ($scanlines) {
                   7470: 	my $prefix='scantron_';
1.157     albertel 7471: # no need to update orig, shouldn't change
                   7472: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7473: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7474: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7475: 			$prefix.'corrected_'.
1.257     albertel 7476: 			$env{'form.scantron_selectfile'});
1.200     albertel 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7478: 			$prefix.'skipped_'.
1.257     albertel 7479: 			$env{'form.scantron_selectfile'});
1.200     albertel 7480:     }
1.175     albertel 7481:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7482: }
                   7483: 
1.423     albertel 7484: =pod
                   7485: 
                   7486: =item scantron_get_line
                   7487: 
1.424     albertel 7488:    Returns the correct version of the scanline
                   7489: 
                   7490:  Arguments:
                   7491:     $scanlines - hash ref that looks like the first return value from
                   7492:                  &scantron_getfile()
                   7493:     $scan_data - hash ref that looks like the second return value from
                   7494:                  &scantron_getfile()
                   7495:     $i         - number of the requested line (starts at 0)
                   7496: 
                   7497:  Returns:
                   7498:    A scanline, (either the original or the corrected one if it
                   7499:    exists), or undef if the requested scanline should be
                   7500:    skipped. (Either because it's an skipped scanline, or it's an
                   7501:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7502:    pass.
                   7503: 
1.423     albertel 7504: =cut
                   7505: 
1.157     albertel 7506: sub scantron_get_line {
1.200     albertel 7507:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7508:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7509:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7510:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7511:     return $scanlines->{'orig'}[$i]; 
                   7512: }
                   7513: 
1.423     albertel 7514: =pod
                   7515: 
                   7516: =item scantron_todo_count
                   7517: 
1.424     albertel 7518:     Counts the number of scanlines that need processing.
                   7519: 
                   7520:  Arguments:
                   7521:     $scanlines - hash ref that looks like the first return value from
                   7522:                  &scantron_getfile()
                   7523:     $scan_data - hash ref that looks like the second return value from
                   7524:                  &scantron_getfile()
                   7525: 
                   7526:  Returns:
                   7527:     $count - number of scanlines to process
                   7528: 
1.423     albertel 7529: =cut
                   7530: 
1.200     albertel 7531: sub get_todo_count {
                   7532:     my ($scanlines,$scan_data)=@_;
                   7533:     my $count=0;
                   7534:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7535: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7536: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7537: 	$count++;
                   7538:     }
                   7539:     return $count;
                   7540: }
                   7541: 
1.423     albertel 7542: =pod
                   7543: 
                   7544: =item scantron_put_line
                   7545: 
1.596.2.6  raeburn  7546:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7547:     data file.
                   7548: 
                   7549:  Arguments:
                   7550:     $scanlines - hash ref that looks like the first return value from
                   7551:                  &scantron_getfile()
                   7552:     $scan_data - hash ref that looks like the second return value from
                   7553:                  &scantron_getfile()
                   7554:     $i         - line number to update
                   7555:     $newline   - contents of the updated scanline
                   7556:     $skip      - if true make the line for skipping and update the
                   7557:                  'skipped' file
                   7558: 
1.423     albertel 7559: =cut
                   7560: 
1.157     albertel 7561: sub scantron_put_line {
1.200     albertel 7562:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7563:     if ($skip) {
                   7564: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7565: 	&start_skipping($scan_data,$i);
1.157     albertel 7566: 	return;
                   7567:     }
                   7568:     $scanlines->{'corrected'}[$i]=$newline;
                   7569: }
                   7570: 
1.423     albertel 7571: =pod
                   7572: 
                   7573: =item scantron_clear_skip
                   7574: 
1.424     albertel 7575:    Remove a line from the 'skipped' file
                   7576: 
                   7577:  Arguments:
                   7578:     $scanlines - hash ref that looks like the first return value from
                   7579:                  &scantron_getfile()
                   7580:     $scan_data - hash ref that looks like the second return value from
                   7581:                  &scantron_getfile()
                   7582:     $i         - line number to update
                   7583: 
1.423     albertel 7584: =cut
                   7585: 
1.376     albertel 7586: sub scantron_clear_skip {
                   7587:     my ($scanlines,$scan_data,$i)=@_;
                   7588:     if (exists($scanlines->{'skipped'}[$i])) {
                   7589: 	undef($scanlines->{'skipped'}[$i]);
                   7590: 	return 1;
                   7591:     }
                   7592:     return 0;
                   7593: }
                   7594: 
1.423     albertel 7595: =pod
                   7596: 
                   7597: =item scantron_filter_not_exam
                   7598: 
1.424     albertel 7599:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7600:    filter out resources that are not marked as 'exam' mode
                   7601: 
1.423     albertel 7602: =cut
                   7603: 
1.334     albertel 7604: sub scantron_filter_not_exam {
                   7605:     my ($curres)=@_;
                   7606:     
                   7607:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7608: 	# if the user has asked to not have either hidden
                   7609: 	# or 'randomout' controlled resources to be graded
                   7610: 	# don't include them
                   7611: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7612: 	    && $curres->randomout) {
                   7613: 	    return 0;
                   7614: 	}
                   7615: 	return 1;
                   7616:     }
                   7617:     return 0;
                   7618: }
                   7619: 
1.423     albertel 7620: =pod
                   7621: 
                   7622: =item scantron_validate_sequence
                   7623: 
1.424     albertel 7624:     Validates the selected sequence, checking for resource that are
                   7625:     not set to exam mode.
                   7626: 
1.423     albertel 7627: =cut
                   7628: 
1.334     albertel 7629: sub scantron_validate_sequence {
                   7630:     my ($r,$currentphase) = @_;
                   7631: 
                   7632:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7633:     unless (ref($navmap)) {
                   7634:         $r->print(&navmap_errormsg());
                   7635:         return (1,$currentphase);
                   7636:     }
1.334     albertel 7637:     my (undef,undef,$sequence)=
                   7638: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7639: 
                   7640:     my $map=$navmap->getResourceByUrl($sequence);
                   7641: 
                   7642:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7643:                                     value="ignore" />');
                   7644:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7645: 	my @resources=
                   7646: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7647: 	if (@resources) {
1.596.2.12.2.  0(raebur 7648:2): 	    $r->print('<p class="LC_warning">'
                   7649:2):                .&mt('Some resources in the sequence currently are not set to'
                   7650:2):                    .' exam mode. Grading these resources currently may not'
                   7651:2):                    .' work correctly.')
                   7652:2):                .'</p>'
                   7653:2):             );
1.334     albertel 7654: 	    return (1,$currentphase);
                   7655: 	}
                   7656:     }
                   7657: 
                   7658:     return (0,$currentphase+1);
                   7659: }
                   7660: 
1.423     albertel 7661: 
                   7662: 
1.157     albertel 7663: sub scantron_validate_ID {
                   7664:     my ($r,$currentphase) = @_;
                   7665:     
                   7666:     #get student info
                   7667:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7668:     my %idmap=&username_to_idmap($classlist);
                   7669: 
                   7670:     #get scantron line setup
1.596.2.12.2.  9(raebur 7671:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7672:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7673: 
                   7674:     my $nav_error;
1.596.2.12.2.  (raeburn 7675:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7676:     if ($nav_error) {
                   7677:         $r->print(&navmap_errormsg());
                   7678:         return(1,$currentphase);
                   7679:     }
1.157     albertel 7680: 
                   7681:     my %found=('ids'=>{},'usernames'=>{});
                   7682:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7683: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7684: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7685: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7686: 						 $scan_data);
                   7687: 	my $id=$$scan_record{'scantron.ID'};
                   7688: 	my $found;
                   7689: 	foreach my $checkid (keys(%idmap)) {
                   7690: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7691: 	}
                   7692: 	if ($found) {
                   7693: 	    my $username=$idmap{$found};
                   7694: 	    if ($found{'ids'}{$found}) {
                   7695: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7696: 					 $line,'duplicateID',$found);
1.194     albertel 7697: 		return(1,$currentphase);
1.157     albertel 7698: 	    } elsif ($found{'usernames'}{$username}) {
                   7699: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7700: 					 $line,'duplicateID',$username);
1.194     albertel 7701: 		return(1,$currentphase);
1.157     albertel 7702: 	    }
1.186     albertel 7703: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7704: 	    $found{'ids'}{$found}++;
                   7705: 	    $found{'usernames'}{$username}++;
                   7706: 	} else {
                   7707: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7708: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7709: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7710: 		    &scantron_get_correction($r,$i,$scan_record,
                   7711: 					     \%scantron_config,
                   7712: 					     $line,'duplicateID',$username);
1.194     albertel 7713: 		    return(1,$currentphase);
1.157     albertel 7714: 		} elsif (!defined($username)) {
                   7715: 		    &scantron_get_correction($r,$i,$scan_record,
                   7716: 					     \%scantron_config,
                   7717: 					     $line,'incorrectID');
1.194     albertel 7718: 		    return(1,$currentphase);
1.157     albertel 7719: 		}
                   7720: 		$found{'usernames'}{$username}++;
                   7721: 	    } else {
                   7722: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7723: 					 $line,'incorrectID');
1.194     albertel 7724: 		return(1,$currentphase);
1.157     albertel 7725: 	    }
                   7726: 	}
                   7727:     }
                   7728: 
                   7729:     return (0,$currentphase+1);
                   7730: }
                   7731: 
1.423     albertel 7732: 
1.157     albertel 7733: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7734:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7735:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7736: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7737: #to show both the current line and the previous one and allow skipping
                   7738: #the previous one or the current one
                   7739: 
1.333     albertel 7740:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7741:         $r->print(
                   7742:             '<p class="LC_warning">'
                   7743:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7744:                 "<b>$error</b>",
                   7745:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7746:            ."</p> \n");
1.157     albertel 7747:     } else {
1.596.2.6  raeburn  7748:         $r->print(
                   7749:             '<p class="LC_warning">'
                   7750:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7751:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7752:            ."</p> \n");
                   7753:     }
                   7754:     my $message =
                   7755:         '<p>'
                   7756:        .&mt('The ID on the form is [_1]',
                   7757:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7758:        .'<br />'
1.596.2.12  raeburn  7759:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7760:             $$scan_record{'scantron.LastName'},
                   7761:             $$scan_record{'scantron.FirstName'})
                   7762:        .'</p>';
1.242     albertel 7763: 
1.157     albertel 7764:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7765:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7766:                            # Array populated for doublebubble or
                   7767:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7768:                            # to validate radio button checking   
                   7769: 
1.157     albertel 7770:     if ($error =~ /ID$/) {
1.186     albertel 7771: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7772: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7773: 		      "</p>\n");
1.157     albertel 7774: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7775: 	    $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 7776: 	}
1.242     albertel 7777: 	$r->print($message);
1.492     albertel 7778: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7779: 	$r->print("\n<ul><li> ");
                   7780: 	#FIXME it would be nice if this sent back the user ID and
                   7781: 	#could do partial userID matches
                   7782: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7783: 				       'scantron_username','scantron_domain'));
                   7784: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7785:3): 	$r->print("\n:\n".
1.257     albertel 7786: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7787: 
                   7788: 	$r->print('</li>');
1.186     albertel 7789:     } elsif ($error =~ /CODE$/) {
                   7790: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7791: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7792: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7793: 	    $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 7794: 	}
1.596.2.6  raeburn  7795:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7796:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7797:                  ."</p>\n");
1.242     albertel 7798: 	$r->print($message);
1.596.2.6  raeburn  7799: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7800: 	$r->print("\n<br /> ");
1.194     albertel 7801: 	my $i=0;
1.273     albertel 7802: 	if ($error eq 'incorrectCODE' 
                   7803: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7804: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7805: 	    if ($closest > 0) {
                   7806: 		foreach my $testcode (@{$closest}) {
                   7807: 		    my $checked='';
1.569     bisitz   7808: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7809: 		    $r->print("
                   7810:    <label>
1.569     bisitz   7811:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7812:        ".&mt("Use the similar CODE [_1] instead.",
                   7813: 	    "<b><tt>".$testcode."</tt></b>")."
                   7814:     </label>
                   7815:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7816: 		    $r->print("\n<br />");
                   7817: 		    $i++;
                   7818: 		}
1.194     albertel 7819: 	    }
                   7820: 	}
1.273     albertel 7821: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7822: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7823: 	    $r->print("
                   7824:     <label>
1.569     bisitz   7825:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7826:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7827: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7828:     </label>");
1.273     albertel 7829: 	    $r->print("\n<br />");
                   7830: 	}
1.194     albertel 7831: 
1.596.2.12.2.  1(raebur 7832:0): 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7833: function change_radio(field) {
1.190     albertel 7834:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7835:     var i;
                   7836:     for (i=0;i<slct.length;i++) {
                   7837:         if (slct[i].value==field) { slct[i].checked=true; }
                   7838:     }
                   7839: }
                   7840: ENDSCRIPT
1.187     albertel 7841: 	my $href="/adm/pickcode?".
1.359     www      7842: 	   "form=".&escape("scantronupload").
                   7843: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7844: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7845: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7846: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7847: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7848: 	    $r->print("
                   7849:     <label>
                   7850:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7851:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7852: 	     "<a target='_blank' href='$href'>","</a>")."
                   7853:     </label> 
1.558     bisitz   7854:     ".&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 7855: 	    $r->print("\n<br />");
                   7856: 	}
1.492     albertel 7857: 	$r->print("
                   7858:     <label>
                   7859:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7860:        ".&mt("Use [_1] as the CODE.",
                   7861: 	     "</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 7862: 	$r->print("\n<br /><br />");
1.157     albertel 7863:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7864: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7865: 
                   7866: 	# The form field scantron_questions is acutally a list of line numbers.
                   7867: 	# represented by this form so:
                   7868: 
1.596.2.12.2.  6(raebur 7869:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7870:3):                                                 $respnumlookup,$startline);
1.497     foxr     7871: 
1.157     albertel 7872: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7873: 		  $line_list.'" />');
1.242     albertel 7874: 	$r->print($message);
1.492     albertel 7875: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7876: 	foreach my $question (@{$arg}) {
1.503     raeburn  7877: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7878:3):                                                    $scan_record, $error,
                   7879:3):                                                    $randomorder,$randompick,
                   7880:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7881:             push(@lines_to_correct,@linenums);
1.157     albertel 7882: 	}
1.503     raeburn  7883:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7884:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7885: 	$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 7886: 	$r->print($message);
1.492     albertel 7887: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7888: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7889: 
1.503     raeburn  7890: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7891: 	# a list of question numbers. Therefore:
                   7892: 	#
                   7893: 	
1.596.2.12.2.  6(raebur 7894:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7895:3):                                                 $respnumlookup,$startline);
1.497     foxr     7896: 
1.157     albertel 7897: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7898: 		  $line_list.'" />');
1.157     albertel 7899: 	foreach my $question (@{$arg}) {
1.503     raeburn  7900: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7901:3):                                                    $scan_record, $error,
                   7902:3):                                                    $randomorder,$randompick,
                   7903:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7904:             push(@lines_to_correct,@linenums);
1.157     albertel 7905: 	}
1.503     raeburn  7906:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7907:     } else {
                   7908: 	$r->print("\n<ul>");
                   7909:     }
                   7910:     $r->print("\n</li></ul>");
1.497     foxr     7911: }
                   7912: 
1.503     raeburn  7913: sub verify_bubbles_checked {
                   7914:     my (@ansnums) = @_;
                   7915:     my $ansnumstr = join('","',@ansnums);
                   7916:     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 7917:6):     &js_escape(\$warning);
          1(raebur 7918:0):     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  7919: function verify_bubble_radio(form) {
                   7920:     var ansnumArray = new Array ("$ansnumstr");
                   7921:     var need_bubble_count = 0;
                   7922:     for (var i=0; i<ansnumArray.length; i++) {
                   7923:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7924:             var bubble_picked = 0; 
                   7925:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7926:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7927:                     bubble_picked = 1;
                   7928:                 }
                   7929:             }
                   7930:             if (bubble_picked == 0) {
                   7931:                 need_bubble_count ++;
                   7932:             }
                   7933:         }
                   7934:     }
                   7935:     if (need_bubble_count) {
                   7936:         alert("$warning");
                   7937:         return;
                   7938:     }
                   7939:     form.submit(); 
                   7940: }
                   7941: ENDSCRIPT
                   7942:     return $output;
                   7943: }
                   7944: 
1.497     foxr     7945: =pod
                   7946: 
                   7947: =item  questions_to_line_list
1.157     albertel 7948: 
1.497     foxr     7949: Converts a list of questions into a string of comma separated
                   7950: line numbers in the answer sheet used by the questions.  This is
                   7951: used to fill in the scantron_questions form field.
                   7952: 
                   7953:   Arguments:
                   7954:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7955:3):      randomorder  - True if randomorder in use.
                   7956:3):      randompick   - True if randompick in use.
                   7957:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7958:3):                      for current line to question number used for same question
                   7959:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7960:3):      startline    - Reference to hash where key is question number (0 is first)
                   7961:3):                     and key is number of first bubble line for current student
                   7962:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7963: 
                   7964: =cut
                   7965: 
                   7966: 
                   7967: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7968:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7969:     my @lines;
                   7970: 
1.503     raeburn  7971:     foreach my $item (@{$questions}) {
                   7972:         my $question = $item;
                   7973:         my ($first,$count,$last);
                   7974:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7975:             $question = $1;
                   7976:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7977:3):             my $responsenum = $question-1;
                   7978:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7979:3):                 $responsenum = $respnumlookup->{$question-1};
                   7980:3):                 if (ref($startline) eq 'HASH') {
                   7981:3):                     $first = $startline->{$question-1} + 1;
                   7982:3):                 }
                   7983:3):             } else {
                   7984:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7985:3):             }
          7(raebur 7986:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7987:             my $subcount = 1;
                   7988:             while ($subcount<$subquestion) {
                   7989:                 $first += $subans[$subcount-1];
                   7990:                 $subcount ++;
                   7991:             }
                   7992:             $count = $subans[$subquestion-1];
                   7993:         } else {
1.596.2.12.2.  7(raebur 7994:3):             my $responsenum = $question-1;
                   7995:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7996:3):                 $responsenum = $respnumlookup->{$question-1};
                   7997:3):                 if (ref($startline) eq 'HASH') {
                   7998:3):                     $first = $startline->{$question-1} + 1;
                   7999:3):                 }
                   8000:3):             } else {
                   8001:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   8002:3):             }
                   8003:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8004:         }
1.506     raeburn  8005:         $last = $first+$count-1;
1.503     raeburn  8006:         push(@lines, ($first..$last));
1.497     foxr     8007:     }
                   8008:     return join(',', @lines);
                   8009: }
                   8010: 
                   8011: =pod 
                   8012: 
                   8013: =item prompt_for_corrections
                   8014: 
                   8015: Prompts for a potentially multiline correction to the
                   8016: user's bubbling (factors out common code from scantron_get_correction
                   8017: for multi and missing bubble cases).
                   8018: 
                   8019:  Arguments:
                   8020:    $r           - Apache request object.
                   8021:    $question    - The question number to prompt for.
                   8022:    $scan_config - The scantron file configuration hash.
                   8023:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8024:    $error       - Type of error
1.596.2.12.2.  7(raebur 8025:3):    $randomorder - True if randomorder in use.
                   8026:3):    $randompick  - True if randompick in use.
                   8027:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8028:3):                     for current line to question number used for same question
                   8029:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   8030:3):    $startline   - Reference to hash where key is question number (0 is first)
                   8031:3):                   and value is number of first bubble line for current student
                   8032:3):                   or code-based randompick and/or randomorder.
1.497     foxr     8033: 
                   8034:  Implicit inputs:
                   8035:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8036:                                   Numbered from 0 (but question numbers are from
                   8037:                                   1.
                   8038:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8039:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8040:                                   type problems render as separate sub-questions, 
1.503     raeburn  8041:                                   in exam mode. This hash contains a 
                   8042:                                   comma-separated list of the lines per 
                   8043:                                   sub-question.
1.510     raeburn  8044:    %responsetype_per_response   - essayresponse, formularesponse,
                   8045:                                   stringresponse, imageresponse, reactionresponse,
                   8046:                                   and organicresponse type problem parts can have
1.503     raeburn  8047:                                   multiple lines per response if the weight
                   8048:                                   assigned exceeds 10.  In this case, only
                   8049:                                   one bubble per line is permitted, but more 
                   8050:                                   than one line might contain bubbles, e.g.
                   8051:                                   bubbling of: line 1 - J, line 2 - J, 
                   8052:                                   line 3 - B would assign 22 points.  
1.497     foxr     8053: 
                   8054: =cut
                   8055: 
                   8056: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8057:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8058:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8059:     my ($current_line,$lines);
                   8060:     my @linenums;
                   8061:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8062:3):     my ($first,$responsenum);
1.503     raeburn  8063:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8064:         $question = $1;
                   8065:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8066:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8067:3):             $responsenum = $respnumlookup->{$question-1};
                   8068:3):             if (ref($startline) eq 'HASH') {
                   8069:3):                 $first = $startline->{$question-1};
                   8070:3):             }
                   8071:3):         } else {
                   8072:3):             $responsenum = $question-1;
          7(raebur 8073:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8074:3):         }
                   8075:3):         $current_line = $first + 1 ;
                   8076:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8077:         my $subcount = 1;
                   8078:         while ($subcount<$subquestion) {
                   8079:             $current_line += $subans[$subcount-1];
                   8080:             $subcount ++;
                   8081:         }
                   8082:         $lines = $subans[$subquestion-1];
                   8083:     } else {
1.596.2.12.2.  6(raebur 8084:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8085:3):             $responsenum = $respnumlookup->{$question-1};
                   8086:3):             if (ref($startline) eq 'HASH') {
                   8087:3):                 $first = $startline->{$question-1};
                   8088:3):             }
                   8089:3):         } else {
                   8090:3):             $responsenum = $question-1;
                   8091:3):             $first = $first_bubble_line{$responsenum};
                   8092:3):         }
                   8093:3):         $current_line = $first + 1;
                   8094:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8095:     }
1.497     foxr     8096:     if ($lines > 1) {
1.503     raeburn  8097:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8098:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8099:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8100:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8101:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8102:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8103:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8104: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  8105:         } else {
                   8106:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8107:         }
1.497     foxr     8108:     }
                   8109:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8110:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8111:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8112: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8113:         push(@linenums,$current_line);
1.497     foxr     8114: 	$current_line++;
                   8115:     }
                   8116:     if ($lines > 1) {
                   8117: 	$r->print("<hr /><br />");
                   8118:     }
1.503     raeburn  8119:     return @linenums;
1.157     albertel 8120: }
1.423     albertel 8121: 
                   8122: =pod
                   8123: 
                   8124: =item scantron_bubble_selector
                   8125:   
                   8126:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8127:    possibly showing the existing the selected bubbles if known
1.423     albertel 8128: 
                   8129:  Arguments:
                   8130:     $r           - Apache request object
1.596.2.12.2.  9(raebur 8131:9):     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8132:     $line        - Number of the line being displayed.
1.503     raeburn  8133:     $questionnum - Question number (may include subquestion)
                   8134:     $error       - Type of error.
1.497     foxr     8135:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8136: 
                   8137: =cut
                   8138: 
1.157     albertel 8139: sub scantron_bubble_selector {
1.503     raeburn  8140:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8141:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8142: 
                   8143:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8144:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8145:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8146:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8147:):             $max=$$scan_config{'BubblesPerRow'};
                   8148:):             if (($scmode eq 'number') && ($max > 10)) {
                   8149:):                 $max = 10;
                   8150:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8151:):                 $max = 26;
                   8152:):             }
                   8153:):         } else {
                   8154:):             $max = 10;
                   8155:):         }
                   8156:):     }
1.274     albertel 8157: 
1.157     albertel 8158:     my @alphabet=('A'..'Z');
1.503     raeburn  8159:     $r->print(&Apache::loncommon::start_data_table().
                   8160:               &Apache::loncommon::start_data_table_row());
                   8161:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8162:     for (my $i=0;$i<$max+1;$i++) {
                   8163: 	$r->print("\n".'<td align="center">');
                   8164: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8165: 	else { $r->print('&nbsp;'); }
                   8166: 	$r->print('</td>');
                   8167:     }
1.503     raeburn  8168:     $r->print(&Apache::loncommon::end_data_table_row().
                   8169:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8170:     for (my $i=0;$i<$max;$i++) {
                   8171: 	$r->print("\n".
                   8172: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8173: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8174:     }
1.503     raeburn  8175:     my $nobub_checked = ' ';
                   8176:     if ($error eq 'missingbubble') {
                   8177:         $nobub_checked = ' checked = "checked" ';
                   8178:     }
                   8179:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8180: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8181:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8182:               $line.'" value="'.$questionnum.'" /></td>');
                   8183:     $r->print(&Apache::loncommon::end_data_table_row().
                   8184:               &Apache::loncommon::end_data_table());
1.157     albertel 8185: }
                   8186: 
1.423     albertel 8187: =pod
                   8188: 
                   8189: =item num_matches
                   8190: 
1.424     albertel 8191:    Counts the number of characters that are the same between the two arguments.
                   8192: 
                   8193:  Arguments:
                   8194:    $orig - CODE from the scanline
                   8195:    $code - CODE to match against
                   8196: 
                   8197:  Returns:
                   8198:    $count - integer count of the number of same characters between the
                   8199:             two arguments
                   8200: 
1.423     albertel 8201: =cut
                   8202: 
1.194     albertel 8203: sub num_matches {
                   8204:     my ($orig,$code) = @_;
                   8205:     my @code=split(//,$code);
                   8206:     my @orig=split(//,$orig);
                   8207:     my $same=0;
                   8208:     for (my $i=0;$i<scalar(@code);$i++) {
                   8209: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8210:     }
                   8211:     return $same;
                   8212: }
                   8213: 
1.423     albertel 8214: =pod
                   8215: 
                   8216: =item scantron_get_closely_matching_CODEs
                   8217: 
1.424     albertel 8218:    Cycles through all CODEs and finds the set that has the greatest
                   8219:    number of same characters as the provided CODE
                   8220: 
                   8221:  Arguments:
                   8222:    $allcodes - hash ref returned by &get_codes()
                   8223:    $CODE     - CODE from the current scanline
                   8224: 
                   8225:  Returns:
                   8226:    2 element list
                   8227:     - first elements is number of how closely matching the best fit is 
                   8228:       (5 means best set has 5 matching characters)
                   8229:     - second element is an arrary ref containing the set of valid CODEs
                   8230:       that best fit the passed in CODE
                   8231: 
1.423     albertel 8232: =cut
                   8233: 
1.194     albertel 8234: sub scantron_get_closely_matching_CODEs {
                   8235:     my ($allcodes,$CODE)=@_;
                   8236:     my @CODEs;
                   8237:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8238: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8239:     }
                   8240: 
                   8241:     return ($#CODEs,$CODEs[-1]);
                   8242: }
                   8243: 
1.423     albertel 8244: =pod
                   8245: 
                   8246: =item get_codes
                   8247: 
1.424     albertel 8248:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8249:    set of remembered CODEs.
                   8250: 
                   8251:  Arguments:
                   8252:   $old_name - name of the set of remembered CODEs
                   8253:   $cdom     - domain of the course
                   8254:   $cnum     - internal course name
                   8255: 
                   8256:  Returns:
                   8257:   %allcodes - keys are the valid CODEs, values are all 1
                   8258: 
1.423     albertel 8259: =cut
                   8260: 
1.194     albertel 8261: sub get_codes {
1.280     foxr     8262:     my ($old_name, $cdom, $cnum) = @_;
                   8263:     if (!$old_name) {
                   8264: 	$old_name=$env{'form.scantron_CODElist'};
                   8265:     }
                   8266:     if (!$cdom) {
                   8267: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8268:     }
                   8269:     if (!$cnum) {
                   8270: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8271:     }
1.278     albertel 8272:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8273: 				    $cdom,$cnum);
                   8274:     my %allcodes;
                   8275:     if ($result{"type\0$old_name"} eq 'number') {
                   8276: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8277:     } else {
                   8278: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8279:     }
1.194     albertel 8280:     return %allcodes;
                   8281: }
                   8282: 
1.423     albertel 8283: =pod
                   8284: 
                   8285: =item scantron_validate_CODE
                   8286: 
1.424     albertel 8287:    Validates all scanlines in the selected file to not have any
                   8288:    invalid or underspecified CODEs and that none of the codes are
                   8289:    duplicated if this was requested.
                   8290: 
1.423     albertel 8291: =cut
                   8292: 
1.157     albertel 8293: sub scantron_validate_CODE {
                   8294:     my ($r,$currentphase) = @_;
1.596.2.12.2.  9(raebur 8295:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8296:     if ($scantron_config{'CODElocation'} &&
                   8297: 	$scantron_config{'CODEstart'} &&
                   8298: 	$scantron_config{'CODElength'}) {
1.257     albertel 8299: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8300: 	    &FIXME_blow_up()
                   8301: 	}
                   8302:     } else {
                   8303: 	return (0,$currentphase+1);
                   8304:     }
                   8305:     
                   8306:     my %usedCODEs;
                   8307: 
1.194     albertel 8308:     my %allcodes=&get_codes();
1.186     albertel 8309: 
1.582     raeburn  8310:     my $nav_error;
1.596.2.12.2.  (raeburn 8311:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8312:     if ($nav_error) {
                   8313:         $r->print(&navmap_errormsg());
                   8314:         return(1,$currentphase);
                   8315:     }
1.447     foxr     8316: 
1.186     albertel 8317:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8318:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8319: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8320: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8321: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8322: 						 $scan_data);
                   8323: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8324: 	my $error=0;
1.224     albertel 8325: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8326: 	    &scantron_get_correction($r,$i,$scan_record,
                   8327: 				     \%scantron_config,
                   8328: 				     $line,'incorrectCODE',\%allcodes);
                   8329: 	    return(1,$currentphase);
                   8330: 	}
1.221     albertel 8331: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8332: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8333: 	    &scantron_get_correction($r,$i,$scan_record,
                   8334: 				     \%scantron_config,
1.194     albertel 8335: 				     $line,'incorrectCODE',\%allcodes);
                   8336: 	    return(1,$currentphase);
1.186     albertel 8337: 	}
1.214     albertel 8338: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8339: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8340: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8341: 	    &scantron_get_correction($r,$i,$scan_record,
                   8342: 				     \%scantron_config,
1.194     albertel 8343: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8344: 	    return(1,$currentphase);
1.186     albertel 8345: 	}
1.524     raeburn  8346: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8347:     }
1.157     albertel 8348:     return (0,$currentphase+1);
                   8349: }
                   8350: 
1.423     albertel 8351: =pod
                   8352: 
                   8353: =item scantron_validate_doublebubble
                   8354: 
1.424     albertel 8355:    Validates all scanlines in the selected file to not have any
                   8356:    bubble lines with multiple bubbles marked.
                   8357: 
1.423     albertel 8358: =cut
                   8359: 
1.157     albertel 8360: sub scantron_validate_doublebubble {
                   8361:     my ($r,$currentphase) = @_;
                   8362:     #get student info
                   8363:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8364:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8365:3):     my (undef,undef,$sequence)=
                   8366:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8367: 
                   8368:     #get scantron line setup
1.596.2.12.2.  9(raebur 8369:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8370:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8371:3): 
                   8372:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8373:3):     unless (ref($navmap)) {
                   8374:3):         $r->print(&navmap_errormsg());
                   8375:3):         return(1,$currentphase);
                   8376:3):     }
                   8377:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8378:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8379:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8380:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8381:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8382:3): 
1.583     raeburn  8383:     my $nav_error;
1.596.2.12.2.  6(raebur 8384:3):     if (ref($map)) {
                   8385:3):         $randomorder = $map->randomorder();
                   8386:3):         $randompick = $map->randompick();
                   8387:3):         if ($randomorder || $randompick) {
                   8388:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8389:3):             if ($nav_error) {
                   8390:3):                 $r->print(&navmap_errormsg());
                   8391:3):                 return(1,$currentphase);
                   8392:3):             }
                   8393:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8394:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8395:3):         }
                   8396:3):     } else {
                   8397:3):         $r->print(&navmap_errormsg());
                   8398:3):         return(1,$currentphase);
                   8399:3):     }
                   8400:3): 
          (raeburn 8401:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8402:     if ($nav_error) {
                   8403:         $r->print(&navmap_errormsg());
                   8404:         return(1,$currentphase);
                   8405:     }
1.447     foxr     8406: 
1.157     albertel 8407:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8408: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8409: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8410: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8411:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8412:3):                                                  $randompick,$sequence,\@master_seq,
                   8413:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8414:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8415: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8416: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8417: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8418:3): 				 $$scan_record{'scantron.doubleerror'},
                   8419:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8420:     	return (1,$currentphase);
                   8421:     }
                   8422:     return (0,$currentphase+1);
                   8423: }
                   8424: 
1.423     albertel 8425: 
1.503     raeburn  8426: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8427:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8428:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8429: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8430: 	&restore_bubble_lines();
1.257     albertel 8431: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8432:     }
1.330     albertel 8433: 
1.447     foxr     8434:     my (undef, undef, $sequence) =
1.257     albertel 8435: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8436: 
1.447     foxr     8437:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8438:     unless (ref($navmap)) {
                   8439:         if (ref($nav_error)) {
                   8440:             $$nav_error = 1;
                   8441:         }
1.591     raeburn  8442:         return;
1.582     raeburn  8443:     }
1.191     albertel 8444:     my $map=$navmap->getResourceByUrl($sequence);
                   8445:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8446:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8447: 
                   8448:     &Apache::lonxml::clear_problem_counter();
                   8449: 
1.557     raeburn  8450:     my $uname       = $env{'user.name'};
                   8451:     my $udom        = $env{'user.domain'};
1.435     foxr     8452:     my $cid         = $env{'request.course.id'};
                   8453:     my $total_lines = 0;
                   8454:     %bubble_lines_per_response = ();
1.447     foxr     8455:     %first_bubble_line         = ();
1.503     raeburn  8456:     %subdivided_bubble_lines   = ();
                   8457:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8458:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8459: 
1.447     foxr     8460:     my $response_number = 0;
                   8461:     my $bubble_line     = 0;
1.191     albertel 8462:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8463:3):         my $resid = $resource->id();
          (raeburn 8464:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8465:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8466:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8467: 	    foreach my $part_id (@{$parts}) {
                   8468:                 my $lines;
                   8469: 
                   8470: 	        # TODO - make this a persistent hash not an array.
                   8471: 
                   8472:                 # optionresponse, matchresponse and rankresponse type items 
                   8473:                 # render as separate sub-questions in exam mode.
                   8474:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8475:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8476:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8477:                     my ($numbub,$numshown);
                   8478:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8479:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8480:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8481:                         }
                   8482:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8483:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8484:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8485:                         }
                   8486:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8487:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8488:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8489:                         }
                   8490:                     }
                   8491:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8492:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8493:                     }
1.596.2.12.2.  (raeburn 8494:):                     my $bubbles_per_row =
                   8495:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8496:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8497:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8498:                         $inner_bubble_lines++;
                   8499:                     }
                   8500:                     for (my $i=0; $i<$numshown; $i++) {
                   8501:                         $subdivided_bubble_lines{$response_number} .= 
                   8502:                             $inner_bubble_lines.',';
                   8503:                     }
                   8504:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8505:                     $lines = $numshown * $inner_bubble_lines;
                   8506:                 } else {
                   8507:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8508:):                 }
1.542     raeburn  8509: 
                   8510:                 $first_bubble_line{$response_number} = $bubble_line;
                   8511: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8512:                 $responsetype_per_response{$response_number} = 
                   8513:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8514:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8515: 	        $response_number++;
                   8516: 
                   8517: 	        $bubble_line +=  $lines;
                   8518: 	        $total_lines +=  $lines;
                   8519: 	    }
                   8520:         }
                   8521:     }
1.552     raeburn  8522:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8523: 
                   8524:     &save_bubble_lines();
                   8525:     $env{'form.scantron_maxbubble'} =
                   8526: 	$total_lines;
                   8527:     return $env{'form.scantron_maxbubble'};
                   8528: }
1.523     raeburn  8529: 
1.596.2.12.2.  (raeburn 8530:): sub bubblesheet_bubbles_per_row {
                   8531:):     my ($scantron_config) = @_;
                   8532:):     my $bubbles_per_row;
                   8533:):     if (ref($scantron_config) eq 'HASH') {
                   8534:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8535:):     }
                   8536:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8537:):         $bubbles_per_row = 10;
                   8538:):     }
                   8539:):     return $bubbles_per_row;
                   8540:): }
                   8541:): 
1.157     albertel 8542: sub scantron_validate_missingbubbles {
                   8543:     my ($r,$currentphase) = @_;
                   8544:     #get student info
                   8545:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8546:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8547:3):     my (undef,undef,$sequence)=
                   8548:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8549: 
                   8550:     #get scantron line setup
1.596.2.12.2.  9(raebur 8551:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8552:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8553:3): 
                   8554:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8555:3):     unless (ref($navmap)) {
                   8556:3):         $r->print(&navmap_errormsg());
                   8557:3):         return(1,$currentphase);
                   8558:3):     }
                   8559:3): 
                   8560:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8561:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8562:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8563:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8564:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8565:3): 
1.582     raeburn  8566:     my $nav_error;
1.596.2.12.2.  6(raebur 8567:3):     if (ref($map)) {
                   8568:3):         $randomorder = $map->randomorder();
                   8569:3):         $randompick = $map->randompick();
          7(raebur 8570:3):         if ($randomorder || $randompick) {
                   8571:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8572:3):             if ($nav_error) {
                   8573:3):                 $r->print(&navmap_errormsg());
                   8574:3):                 return(1,$currentphase);
                   8575:3):             }
                   8576:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8577:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8578:3):         }
          6(raebur 8579:3):     } else {
                   8580:3):         $r->print(&navmap_errormsg());
          7(raebur 8581:3):         return(1,$currentphase);
          6(raebur 8582:3):     }
                   8583:3): 
                   8584:3): 
          (raeburn 8585:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8586:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8587:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8588:         return(1,$currentphase);
                   8589:     }
1.596.2.12.2.  6(raebur 8590:3): 
1.157     albertel 8591:     if (!$max_bubble) { $max_bubble=2**31; }
                   8592:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8593: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8594: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8595:3):         my $scan_record =
                   8596:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8597:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8598:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8599:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8600: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8601: 	my @to_correct;
1.470     foxr     8602: 	
                   8603: 	# Probably here's where the error is...
                   8604: 
1.157     albertel 8605: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8606:             my $lastbubble;
                   8607:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8608:3):                 my $question = $1;
                   8609:3):                 my $subquestion = $2;
                   8610:3):                 my ($first,$responsenum);
                   8611:3):                 if ($randomorder || $randompick) {
                   8612:3):                     $responsenum = $respnumlookup{$question-1};
                   8613:3):                     $first = $startline{$question-1};
                   8614:3):                 } else {
                   8615:3):                     $responsenum = $question-1;
                   8616:3):                     $first = $first_bubble_line{$responsenum};
                   8617:3):                 }
                   8618:3):                 if (!defined($first)) { next; }
          7(raebur 8619:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8620:3):                 my $subcount = 1;
                   8621:3):                 while ($subcount<$subquestion) {
                   8622:3):                     $first += $subans[$subcount-1];
                   8623:3):                     $subcount ++;
                   8624:3):                 }
                   8625:3):                 my $count = $subans[$subquestion-1];
                   8626:3):                 $lastbubble = $first + $count;
1.505     raeburn  8627:             } else {
1.596.2.12.2.  6(raebur 8628:3):                 my ($first,$responsenum);
                   8629:3):                 if ($randomorder || $randompick) {
                   8630:3):                     $responsenum = $respnumlookup{$missing-1};
                   8631:3):                     $first = $startline{$missing-1};
                   8632:3):                 } else {
                   8633:3):                     $responsenum = $missing-1;
                   8634:3):                     $first = $first_bubble_line{$responsenum};
                   8635:3):                 }
                   8636:3):                 if (!defined($first)) { next; }
                   8637:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8638:             }
                   8639:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8640: 	    push(@to_correct,$missing);
                   8641: 	}
                   8642: 	if (@to_correct) {
                   8643: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8644:3): 				     $line,'missingbubble',\@to_correct,
                   8645:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8646:3):                                      \%startline);
1.157     albertel 8647: 	    return (1,$currentphase);
                   8648: 	}
                   8649: 
                   8650:     }
                   8651:     return (0,$currentphase+1);
                   8652: }
                   8653: 
1.596.2.12.2.  (raeburn 8654:): sub hand_bubble_option {
                   8655:):     my (undef, undef, $sequence) =
                   8656:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8657:):     return if ($sequence eq '');
                   8658:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8659:):     unless (ref($navmap)) {
                   8660:):         return;
                   8661:):     }
                   8662:):     my $needs_hand_bubbles;
                   8663:):     my $map=$navmap->getResourceByUrl($sequence);
                   8664:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8665:):     foreach my $res (@resources) {
                   8666:):         if (ref($res)) {
                   8667:):             if ($res->is_problem()) {
                   8668:):                 my $partlist = $res->parts();
                   8669:):                 foreach my $part (@{ $partlist }) {
                   8670:):                     my @types = $res->responseType($part);
                   8671:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8672:):                         $needs_hand_bubbles = 1;
                   8673:):                         last;
                   8674:):                     }
                   8675:):                 }
                   8676:):             }
                   8677:):         }
                   8678:):     }
                   8679:):     if ($needs_hand_bubbles) {
          9(raebur 8680:9):         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 8681:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8682:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8683:):                &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 />').
                   8684:):                '<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 8685:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8686:):     }
                   8687:):     return;
                   8688:): }
1.423     albertel 8689: 
1.82      albertel 8690: sub scantron_process_students {
1.596.2.12.2.  1(raebur 8691:0):     my ($r,$symb) = @_;
1.513     foxr     8692: 
1.257     albertel 8693:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8694:     if (!$symb) {
                   8695: 	return '';
                   8696:     }
1.324     albertel 8697:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8698: 
1.596.2.12.2.  9(raebur 8699:9):     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          6(raebur 8700:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8701:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8702:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8703:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8704:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8705:     unless (ref($navmap)) {
                   8706:         $r->print(&navmap_errormsg());
                   8707:         return '';
1.596.2.12.2.  6(raebur 8708:3):     }
1.83      albertel 8709:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8710:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8711:3):         %grader_randomlists_by_symb);
          1(raebur 8712:2):     if (ref($map)) {
                   8713:2):         $randomorder = $map->randomorder();
          6(raebur 8714:3):         $randompick = $map->randompick();
                   8715:3):     } else {
                   8716:3):         $r->print(&navmap_errormsg());
                   8717:3):         return '';
          1(raebur 8718:2):     }
          6(raebur 8719:3):     my $nav_error;
1.83      albertel 8720:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8721:3):     if ($randomorder || $randompick) {
                   8722:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8723:3):         if ($nav_error) {
                   8724:3):             $r->print(&navmap_errormsg());
                   8725:3):             return '';
1.586     raeburn  8726:         }
                   8727:     }
1.596.2.12.2.  6(raebur 8728:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8729:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8730: 
1.554     raeburn  8731:     my ($uname,$udom);
1.82      albertel 8732:     my $result= <<SCANTRONFORM;
1.81      albertel 8733: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8734:   <input type="hidden" name="command" value="scantron_configphase" />
                   8735:   $default_form_data
                   8736: SCANTRONFORM
1.82      albertel 8737:     $r->print($result);
                   8738: 
                   8739:     my @delayqueue;
1.542     raeburn  8740:     my (%completedstudents,%scandata);
1.140     albertel 8741:     
1.520     www      8742:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8743:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8744:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          1(raebur 8745:0):     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8746:     $r->print('<br />');
1.140     albertel 8747:     my $start=&Time::HiRes::time();
1.158     albertel 8748:     my $i=-1;
1.542     raeburn  8749:     my $started;
1.447     foxr     8750: 
1.596.2.12.2.  (raeburn 8751:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8752:     if ($nav_error) {
                   8753:         $r->print(&navmap_errormsg());
                   8754:         return '';
                   8755:     }
                   8756: 
1.513     foxr     8757:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8758:     # the user and return.
                   8759: 
                   8760:     if ($ssi_error) {
                   8761: 	$r->print("</form>");
                   8762: 	&ssi_print_error($r);
1.520     www      8763:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8764: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8765:     }
1.447     foxr     8766: 
1.596.2.12.2.  9(raebur 8767:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8768:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8769:3):     my %orderedforcode;
1.542     raeburn  8770: 
1.157     albertel 8771:     while ($i<$scanlines->{'count'}) {
                   8772:  	($uname,$udom)=('','');
                   8773:  	$i++;
1.200     albertel 8774:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8775:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8776: 	if ($started) {
1.596.2.12.2.  1(raebur 8777:0): 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8778: 	}
                   8779: 	$started=1;
1.596.2.12.2.  6(raebur 8780:3):         my %respnumlookup = ();
                   8781:3):         my %startline = ();
                   8782:3):         my $total;
1.157     albertel 8783:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8784:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8785:3):                                                  $randompick,$sequence,\@master_seq,
                   8786:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8787:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8788:3):                                                  \$total);
1.157     albertel 8789:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8790:  					      \%idmap,$i)) {
                   8791:   	    &scantron_add_delay(\@delayqueue,$line,
                   8792:  				'Unable to find a student that matches',1);
                   8793:  	    next;
                   8794:   	}
                   8795:  	if (exists $completedstudents{$uname}) {
                   8796:  	    &scantron_add_delay(\@delayqueue,$line,
                   8797:  				'Student '.$uname.' has multiple sheets',2);
                   8798:  	    next;
                   8799:  	}
1.596.2.12.2.  1(raebur 8800:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8801:2):         my $user = $uname.':'.$usec;
1.157     albertel 8802:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8803: 
1.596.2.12.2.  1(raebur 8804:2):         my $scancode;
                   8805:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8806:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8807:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8808:2):         } else {
                   8809:2):             $scancode = '';
                   8810:2):         }
                   8811:2): 
                   8812:2):         my @mapresources = @resources;
          6(raebur 8813:3):         if ($randomorder || $randompick) {
          1(raebur 8814:2):             @mapresources =
          6(raebur 8815:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8816:3):                              \%orderedforcode);
          1(raebur 8817:2):         }
1.586     raeburn  8818:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8819:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8820:             my $ressymb;
                   8821:             if (ref($resource)) {
                   8822:                 $ressymb = $resource->symb();
                   8823:             } else {
                   8824:                 $res_error = 1;
                   8825:                 last;
                   8826:             }
1.557     raeburn  8827:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8828:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 8829:7):                 my $currcode;
                   8830:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8831:7):                     $currcode = $scancode;
                   8832:7):                 }
1.557     raeburn  8833:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8834:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
          1(raebur 8835:7):                                               $uname,$udom,undef,$bubbles_per_row,
                   8836:7):                                               $currcode);
1.557     raeburn  8837:                 $partids_by_symb{$ressymb} = $parts;
                   8838:             } else {
                   8839:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8840:             }
1.554     raeburn  8841:         }
                   8842: 
1.586     raeburn  8843:         if ($res_error) {
                   8844:             &scantron_add_delay(\@delayqueue,$line,
                   8845:                                 'An error occurred while grading student '.$uname,2);
                   8846:             next;
                   8847:         }
                   8848: 
1.330     albertel 8849: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8850:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8851: 
                   8852: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8853: 	    &scantron_putfile($scanlines,$scan_data);
                   8854: 	}
1.161     albertel 8855: 	
1.542     raeburn  8856:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8857:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8858:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8859:3):                                    \%respnumlookup,\%startline) 
                   8860:3):             eq 'ssi_error') {
1.542     raeburn  8861:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8862:             $r->print("</form>");
                   8863:             &ssi_print_error($r);
                   8864:             &Apache::lonnet::remove_lock($lock);
                   8865:             return '';      # Why return ''?  Beats me.
                   8866:         }
1.513     foxr     8867: 
1.596.2.12.2.  6(raebur 8868:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8869:3):             my $parmresult =
                   8870:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8871:3):                                                        '0_examcode',2,$scancode,
                   8872:3):                                                        'string_examcode',$uname,
                   8873:3):                                                        $udom);
                   8874:3):         }
1.140     albertel 8875: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8876:         if ($env{'form.verifyrecord'}) {
                   8877:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8878:3):             if ($randompick) {
                   8879:3):                 if ($total) {
                   8880:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8881:3):                 }
                   8882:3):             }
                   8883:3): 
1.542     raeburn  8884:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8885:             chomp($studentdata);
                   8886:             $studentdata =~ s/\r$//;
                   8887:             my $studentrecord = '';
                   8888:             my $counter = -1;
1.596.2.12.2.  1(raebur 8889:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8890:                 my $ressymb = $resource->symb();
1.542     raeburn  8891:                 ($counter,my $recording) =
                   8892:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8893:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8894:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8895:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8896:                 $studentrecord .= $recording;
                   8897:             }
                   8898:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8899:                 &Apache::lonxml::clear_problem_counter();
                   8900:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8901:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8902:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8903:3):                                            \%respnumlookup,\%startline)
                   8904:3):                     eq 'ssi_error') {
1.554     raeburn  8905:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8906:                     $r->print("</form>");
                   8907:                     &ssi_print_error($r);
                   8908:                     &Apache::lonnet::remove_lock($lock);
                   8909:                     delete($completedstudents{$uname});
                   8910:                     return '';
                   8911:                 }
1.542     raeburn  8912:                 $counter = -1;
                   8913:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8914:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8915:                     my $ressymb = $resource->symb();
1.542     raeburn  8916:                     ($counter,my $recording) =
                   8917:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8918:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8919:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8920:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8921:3):                                                  \%startline);
1.542     raeburn  8922:                     $studentrecord .= $recording;
                   8923:                 }
                   8924:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8925:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8926:                     if ($scancode eq '') {
1.596.2.6  raeburn  8927:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8928:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8929:                     } else {
1.596.2.6  raeburn  8930:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8931:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8932:                     }
                   8933:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8934:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8935:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8936:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8937:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8938:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8939:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8940:                               &Apache::loncommon::end_data_table_row().
                   8941:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8942:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8943:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8944:                               &Apache::loncommon::end_data_table_row().
                   8945:                               &Apache::loncommon::end_data_table().'</p>');
                   8946:                 } else {
                   8947:                     $r->print('<br /><span class="LC_warning">'.
                   8948:                              &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 />'.
                   8949:                              &mt("As a consequence, this user's submission history records two tries.").
                   8950:                                  '</span><br />');
                   8951:                 }
                   8952:             }
                   8953:         }
1.543     raeburn  8954:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8955:     } continue {
1.330     albertel 8956: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8957: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8958:     }
1.140     albertel 8959:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8960:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8961: #    my $lasttime = &Time::HiRes::time()-$start;
                   8962: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8963: 
1.200     albertel 8964:     $r->print("</form>");
1.157     albertel 8965:     return '';
1.75      albertel 8966: }
1.157     albertel 8967: 
1.557     raeburn  8968: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8969:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8970:):         $bubbles_per_row) = @_;
1.557     raeburn  8971:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8972:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8973:         foreach my $resource (@{$resources}) {
                   8974:             my $ressymb = $resource->symb();
                   8975:             my ($analysis,$parts) =
                   8976:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8977:):                                           $env{'user.name'},$env{'user.domain'},
                   8978:):                                           1,$bubbles_per_row);
1.557     raeburn  8979:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8980:             if (ref($analysis) eq 'HASH') {
                   8981:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8982:                     $grader_randomlists_by_symb->{$ressymb} =
                   8983:                         $analysis->{'parts_withrandomlist'};
                   8984:                 }
                   8985:             }
                   8986:         }
                   8987:     }
                   8988:     return;
                   8989: }
                   8990: 
1.596.2.12.2.  1(raebur 8991:2): =pod
                   8992:2): 
                   8993:2): =item users_order
                   8994:2): 
                   8995:2):   Returns array of resources in current map, ordered based on either CODE,
                   8996:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8997:2):   "NAMEd" exam.
                   8998:2): 
          6(raebur 8999:3):   Should be used when randomorder and/or randompick applied when the 
                   9000:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   9001:3):   for the version of the exam the student received.
          1(raebur 9002:2): 
                   9003:2): =cut
                   9004:2): 
                   9005:2): sub users_order  {
          6(raebur 9006:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 9007:2):     my @mapresources;
          6(raebur 9008:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 9009:2):         return @mapresources;
                   9010:2):     }
          6(raebur 9011:3):     if ($scancode) {
                   9012:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9013:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   9014:3):         } else {
                   9015:3):             $env{'form.CODE'} = $scancode;
                   9016:3):             my $actual_seq =
                   9017:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9018:3):                                                                $master_seq,
                   9019:3):                                                                $user,$scancode,1);
                   9020:3):             if (ref($actual_seq) eq 'ARRAY') {
                   9021:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9022:3):                 if (ref($orderedforcode) eq 'HASH') {
                   9023:3):                     if (@mapresources > 0) {
                   9024:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   9025:3):                     }
                   9026:3):                 }
                   9027:3):             }
                   9028:3):             delete($env{'form.CODE'});
          1(raebur 9029:2):         }
                   9030:2):     } else {
                   9031:2):         my $actual_seq =
                   9032:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9033:2):                                                            $master_seq,
          5(raebur 9034:3):                                                            $user,undef,1);
          1(raebur 9035:2):         if (ref($actual_seq) eq 'ARRAY') {
                   9036:2):             @mapresources =
                   9037:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9038:2):         }
          6(raebur 9039:3):     }
                   9040:3):     return @mapresources;
          1(raebur 9041:2): }
                   9042:2): 
1.542     raeburn  9043: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9044:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9045:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9046:3):     my $uselookup = 0;
                   9047:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9048:3):         (ref($startline) eq 'HASH')) {
                   9049:3):         $uselookup = 1;
                   9050:3):     }
                   9051:3): 
1.554     raeburn  9052:     if (ref($resources) eq 'ARRAY') {
                   9053:         my $count = 0;
                   9054:         foreach my $resource (@{$resources}) {
                   9055:             my $ressymb = $resource->symb();
                   9056:             my %form = ('submitted'      => 'scantron',
                   9057:                         'grade_target'   => 'grade',
                   9058:                         'grade_username' => $uname,
                   9059:                         'grade_domain'   => $udom,
                   9060:                         'grade_courseid' => $env{'request.course.id'},
                   9061:                         'grade_symb'     => $ressymb,
                   9062:                         'CODE'           => $scancode
                   9063:                        );
1.596.2.12.2.  (raeburn 9064:):             if ($bubbles_per_row ne '') {
                   9065:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9066:):             }
                   9067:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9068:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9069:):             }
1.554     raeburn  9070:             if (ref($parts) eq 'HASH') {
                   9071:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9072:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9073:3):                         if ($uselookup) {
                   9074:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9075:3):                         } else {
                   9076:3):                             $form{'scantron_questnum_start.'.$part} =
                   9077:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9078:3):                         }
1.554     raeburn  9079:                         $count++;
                   9080:                     }
                   9081:                 }
                   9082:             }
                   9083:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9084:             return 'ssi_error' if ($ssi_error);
                   9085:             last if (&Apache::loncommon::connection_aborted($r));
                   9086:         }
1.542     raeburn  9087:     }
                   9088:     return;
                   9089: }
                   9090: 
1.157     albertel 9091: sub scantron_upload_scantron_data {
1.596.2.12.2.  1(raebur 9092:0):     my ($r,$symb) = @_;
1.565     raeburn  9093:     my $dom = $env{'request.role.domain'};
1.596.2.12.2.  9(raebur 9094:9):     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9095:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9096:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9097:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9098: 							  'domainid',
1.565     raeburn  9099: 							  'coursename',$dom);
                   9100:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9101:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9102:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9103:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9104:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9105:     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 9106:6):     &js_escape(\$nocourseid_alert);
          9(raebur 9107:9):     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9108:     function checkUpload(formname) {
                   9109: 	if (formname.upfile.value == "") {
1.579     raeburn  9110: 	    alert("'.$nofile_alert.'");
1.157     albertel 9111: 	    return false;
                   9112: 	}
1.565     raeburn  9113:         if (formname.courseid.value == "") {
1.579     raeburn  9114:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9115:             return false;
                   9116:         }
1.157     albertel 9117: 	formname.submit();
                   9118:     }
1.565     raeburn  9119: 
                   9120:     function ToSyllabus() {
                   9121:         var cdom = '."'$dom'".';
                   9122:         var cnum = document.rules.courseid.value;
                   9123:         if (cdom == "" || cdom == null) {
                   9124:             return;
                   9125:         }
                   9126:         if (cnum == "" || cnum == null) {
                   9127:            return;
                   9128:         }
                   9129:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9130:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9131:         return;
                   9132:     }
                   9133: 
1.596.2.12.2.  9(raebur 9134:9):     '.$formatjs.'
                   9135:9): '));
                   9136:9):     $r->print('
1.596.2.4  raeburn  9137: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9138: 
1.492     albertel 9139: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9140: '.$default_form_data.
                   9141:   &Apache::lonhtmlcommon::start_pick_box().
                   9142:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9143:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9144:   &Apache::lonhtmlcommon::row_closure().
                   9145:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9146:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9147:   &Apache::lonhtmlcommon::row_closure().
                   9148:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9149:   '<input name="domainid" type="hidden" />'.$domdesc.
1.596.2.12.2.  9(raebur 9150:9):   &Apache::lonhtmlcommon::row_closure());
                   9151:9):     if ($formatoptions) {
                   9152:9):         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9153:9):                   &Apache::lonhtmlcommon::row_closure());
                   9154:9):     }
                   9155:9):     $r->print(
1.565     raeburn  9156:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9157:   '<input type="file" name="upfile" size="50" />'.
                   9158:   &Apache::lonhtmlcommon::row_closure(1).
                   9159:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9160: 
1.492     albertel 9161: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9162: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9163: </form>
1.492     albertel 9164: ');
1.157     albertel 9165:     return '';
                   9166: }
                   9167: 
1.596.2.12.2.  9(raebur 9168:9): sub scantron_upload_dataformat {
                   9169:9):     my ($dom) = @_;
                   9170:9):     my ($formatoptions,$formattitle,$formatjs);
                   9171:9):     $formatjs = <<'END';
                   9172:9): function toggleScantab(form) {
                   9173:9):    return;
                   9174:9): }
                   9175:9): END
                   9176:9):     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9177:9):     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9178:9):         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9179:9):             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9180:9):                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9181:9):                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
                   9182:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9183:9):                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9184:9):                             my ($onclick,$formatextra,$singleline);
                   9185:9):                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9186:9):                             my $count = 0;
                   9187:9):                             foreach my $line (@lines) {
                   9188:9):                                 next if ($line =~ /^#/);
                   9189:9):                                 $singleline = $line;
                   9190:9):                                 $count ++;
                   9191:9):                             }
                   9192:9):                             if ($count > 1) {
                   9193:9):                                 $formatextra = '<div style="display:none" id="bubbletype">'.
                   9194:9):                                                '<span class="LC_nobreak">'.
                   9195:9):                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9196:9):                                                &scantron_scantab().'</span></div>';
                   9197:9):                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9198:9):                                 $formatjs = <<"END";
                   9199:9): function toggleScantab(form) {
                   9200:9):     var divid = 'bubbletype';
                   9201:9):     if (document.getElementById(divid)) {
                   9202:9):         var radioname = 'fileformat';
                   9203:9):         var num = form.elements[radioname].length;
                   9204:9):         if (num) {
                   9205:9):             for (var i=0; i<num; i++) {
                   9206:9):                 if (form.elements[radioname][i].checked) {
                   9207:9):                     var chosen = form.elements[radioname][i].value;
                   9208:9):                     if (chosen == 'dat') {
                   9209:9):                         document.getElementById(divid).style.display = 'none';
                   9210:9):                     } else if (chosen == 'csv') {
                   9211:9):                         document.getElementById(divid).style.display = 'block';
                   9212:9):                     }
                   9213:9):                 }
                   9214:9):             }
                   9215:9):         }
                   9216:9):     }
                   9217:9):     return;
                   9218:9): }
                   9219:9): 
                   9220:9): END
                   9221:9):                             } elsif ($count == 1) {
                   9222:9):                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9223:9):                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9224:9):                             }
                   9225:9):                             $formattitle = &mt('File format');
                   9226:9):                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9227:9):                                              &mt('Plain Text (no delimiters)').
                   9228:9):                                              '</label>'.('&nbsp;'x2).
                   9229:9):                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9230:9):                                              &mt('Comma separated values').'</label>'.$formatextra;
                   9231:9):                         }
                   9232:9):                     }
                   9233:9):                 }
                   9234:9):             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
                   9235:9):                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9236:9):                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9237:9):                         $formattitle = &mt('Bubblesheet type');
                   9238:9):                         $formatoptions = &scantron_scantab();
                   9239:9):                     }
                   9240:9):                 }
                   9241:9):             }
                   9242:9):         }
                   9243:9):     }
                   9244:9):     return ($formatoptions,$formattitle,$formatjs);
                   9245:9): }
1.423     albertel 9246: 
1.157     albertel 9247: sub scantron_upload_scantron_data_save {
1.596.2.12.2.  1(raebur 9248:0):     my ($r,$symb) = @_;
1.182     albertel 9249:     my $doanotherupload=
                   9250: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9251: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9252: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9253: 	'</form>'."\n";
1.257     albertel 9254:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9255: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9256: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9257: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.596.2.12.2.  1(raebur 9258:0):         unless ($symb) {
1.182     albertel 9259: 	    $r->print($doanotherupload);
                   9260: 	}
1.162     albertel 9261: 	return '';
                   9262:     }
1.257     albertel 9263:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9264:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9265:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9266:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9267:3):         $r->print(
                   9268:3):             &Apache::lonhtmlcommon::confirm_success(
                   9269:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9270:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9271:     } else {
1.596.2.12.2.  9(raebur 9272:9):         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9273:9):         my $parser;
                   9274:9):         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9275:9):             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9276:9):                 my $is_csv;
                   9277:9):                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9278:9):                 if (@possibles > 1) {
                   9279:9):                     if ($env{'form.fileformat'} eq 'csv') {
                   9280:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9281:9):                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9282:9):                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9283:9):                                     $is_csv = 1;
                   9284:9):                                 }
                   9285:9):                             }
                   9286:9):                         }
                   9287:9):                     }
                   9288:9):                 } elsif (@possibles == 1) {
                   9289:9):                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
                   9290:9):                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9291:9):                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9292:9):                                 $is_csv = 1;
                   9293:9):                             }
                   9294:9):                         }
                   9295:9):                     }
                   9296:9):                 }
                   9297:9):                 if ($is_csv) {
                   9298:9):                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9299:9):                 }
                   9300:9):             }
                   9301:9):         }
                   9302:9):         my $result =
                   9303:9):             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9304:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9305: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9306:3):             $r->print(
                   9307:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9308:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9309:3):                         (length($env{'form.upfile'})-1),
                   9310:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9311:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9312:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9313:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9314: 	} else {
1.596.2.12.2.  5(raebur 9315:3):             $r->print(
                   9316:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9317:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9318:3):                           $result,
1.568     raeburn  9319: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9320: 	}
                   9321:     }
1.174     albertel 9322:     if ($symb) {
1.596.2.12.2.  1(raebur 9323:0): 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9324:     } else {
1.182     albertel 9325: 	$r->print($doanotherupload);
1.174     albertel 9326:     }
1.157     albertel 9327:     return '';
                   9328: }
                   9329: 
1.567     raeburn  9330: sub validate_uploaded_scantron_file {
                   9331:     my ($cdom,$cname,$fname) = @_;
                   9332:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9333:     my @lines;
                   9334:     if ($scanlines ne '-1') {
                   9335:         @lines=split("\n",$scanlines,-1);
                   9336:     }
                   9337:     my $output;
                   9338:     if (@lines) {
                   9339:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9340:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9341:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9342:         my %idmap = &username_to_idmap($classlist);
                   9343:         foreach my $key (keys(%idmap)) {
                   9344:             my $lckey = lc($key);
                   9345:             $idmap{$lckey} = $idmap{$key};
                   9346:         }
                   9347:         my %unique_formats;
1.596.2.12.2.  9(raebur 9348:9):         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9349:         foreach my $line (@formatlines) {
                   9350:             chomp($line);
                   9351:             my @config = split(/:/,$line);
                   9352:             my $idstart = $config[5];
                   9353:             my $idlength = $config[6];
                   9354:             if (($idstart ne '') && ($idlength > 0)) {
                   9355:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9356:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9357:                 } else {
                   9358:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9359:                 }
                   9360:             }
                   9361:         }
                   9362:         foreach my $key (keys(%unique_formats)) {
                   9363:             my ($idstart,$idlength) = split(':',$key);
                   9364:             %{$counts{$key}} = (
                   9365:                                'found'   => 0,
                   9366:                                'total'   => 0,
                   9367:                               );
                   9368:             foreach my $line (@lines) {
                   9369:                 next if ($line =~ /^#/);
                   9370:                 next if ($line =~ /^[\s\cz]*$/);
                   9371:                 my $id = substr($line,$idstart-1,$idlength);
                   9372:                 $id = lc($id);
                   9373:                 if (exists($idmap{$id})) {
                   9374:                     $counts{$key}{'found'} ++;
                   9375:                 }
                   9376:                 $counts{$key}{'total'} ++;
                   9377:             }
                   9378:             if ($counts{$key}{'total'}) {
                   9379:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9380:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9381:                     $max_match_pct = $percent_match;
                   9382:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9383:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9384:                     $max_match_count = $counts{$key}{'total'};
                   9385:                 }
                   9386:             }
                   9387:         }
                   9388:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9389:             my $format_descs;
                   9390:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9391:             for (my $i=0; $i<$numwithformat; $i++) {
                   9392:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9393:                 if ($i<$numwithformat-2) {
                   9394:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9395:                 } elsif ($i==$numwithformat-2) {
                   9396:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9397:                 } elsif ($i==$numwithformat-1) {
                   9398:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9399:                 }
                   9400:             }
                   9401:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9402:3):             $output .= '<br />';
                   9403:3):             if ($found_match_count == $max_match_count) {
                   9404:3):                 # 100% matching entries
                   9405:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9406:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9407:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9408:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9409:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9410:3):                     ' in the file (for the format defined for [_3]).',
                   9411:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9412:3):             } else {
                   9413:3):                 # Not all entries matching? -> Show warning and additional info
                   9414:3):                 $output .=
                   9415:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9416:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9417:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9418:3):                         &mt('Not all entries could be matched!'),1).'<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):                     '<p class="LC_info">'.
                   9424:3):                     &mt('A low percentage of matches results from one of the following:').
                   9425:3):                     '</p><ul>'.
                   9426:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9427:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9428:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9429:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9430:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9431:3):                     '</ul>';
                   9432:3):             }
1.567     raeburn  9433:         }
                   9434:     } else {
1.596.2.12.2.  5(raebur 9435:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9436:     }
                   9437:     return $output;
                   9438: }
                   9439: 
1.202     albertel 9440: sub valid_file {
                   9441:     my ($requested_file)=@_;
                   9442:     foreach my $filename (sort(&scantron_filenames())) {
                   9443: 	if ($requested_file eq $filename) { return 1; }
                   9444:     }
                   9445:     return 0;
                   9446: }
                   9447: 
                   9448: sub scantron_download_scantron_data {
1.596.2.12.2.  1(raebur 9449:0):     my ($r,$symb) = @_;
          (raeburn 9450:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9451:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9452:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9453:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9454:     if (! &valid_file($file)) {
1.492     albertel 9455: 	$r->print('
1.202     albertel 9456: 	<p>
1.596.2.12.2.  3(raebur 9457:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9458:         </p>
1.492     albertel 9459: ');
1.202     albertel 9460: 	return;
                   9461:     }
                   9462:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9463:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9464:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9465:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9466:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9467:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9468:     $r->print('
1.202     albertel 9469:     <p>
1.596.2.12.2.  1(raebur 9470:0): 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9471: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9472:     </p>
                   9473:     <p>
1.492     albertel 9474: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9475: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9476:     </p>
                   9477:     <p>
1.492     albertel 9478: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9479: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9480:     </p>
1.492     albertel 9481: ');
1.202     albertel 9482:     return '';
                   9483: }
1.157     albertel 9484: 
1.523     raeburn  9485: sub checkscantron_results {
1.596.2.12.2.  1(raebur 9486:0):     my ($r,$symb) = @_;
1.523     raeburn  9487:     if (!$symb) {return '';}
                   9488:     my $cid = $env{'request.course.id'};
1.596.2.12.2.  9(raebur 9489:9):     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9490:     my $numletts = scalar(keys(%lettdig));
                   9491:     my $cnum = $env{'course.'.$cid.'.num'};
                   9492:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9493:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9494:     my %record;
                   9495:     my %scantron_config =
1.596.2.12.2.  9(raebur 9496:9):         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
          (raeburn 9497:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9498:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9499:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9500:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9501:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9502:     unless (ref($navmap)) {
                   9503:         $r->print(&navmap_errormsg());
                   9504:         return '';
                   9505:     }
1.523     raeburn  9506:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9507:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9508:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9509:2):     if (ref($map)) {
                   9510:2):         $randomorder=$map->randomorder();
          7(raebur 9511:3):         $randompick=$map->randompick();
          1(raebur 9512:2):     }
1.557     raeburn  9513:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9514:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9515:3):     if ($nav_error) {
                   9516:3):         $r->print(&navmap_errormsg());
                   9517:3):         return '';
          1(raebur 9518:2):     }
          (raeburn 9519:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9520:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9521:     my ($uname,$udom);
1.523     raeburn  9522:     my (%scandata,%lastname,%bylast);
                   9523:     $r->print('
                   9524: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9525: 
                   9526:     my @delayqueue;
                   9527:     my %completedstudents;
                   9528: 
1.596.2.12.2.  6(raebur 9529:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9530:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9531:3):     my ($username,$domain,$started);
          (raeburn 9532:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9533:     if ($nav_error) {
                   9534:         $r->print(&navmap_errormsg());
                   9535:         return '';
                   9536:     }
1.523     raeburn  9537: 
                   9538:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9539:                                           'Processing first student');
                   9540:     my $start=&Time::HiRes::time();
                   9541:     my $i=-1;
                   9542: 
                   9543:     while ($i<$scanlines->{'count'}) {
                   9544:         ($username,$domain,$uname)=('','','');
                   9545:         $i++;
                   9546:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9547:         if ($line=~/^[\s\cz]*$/) { next; }
                   9548:         if ($started) {
                   9549:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9550:                                                      'last student');
                   9551:         }
                   9552:         $started=1;
                   9553:         my $scan_record=
                   9554:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9555:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9556:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9557:3):                                               \%idmap,$i)) {
1.523     raeburn  9558:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9559:                                 'Unable to find a student that matches',1);
                   9560:             next;
                   9561:         }
                   9562:         if (exists $completedstudents{$uname}) {
                   9563:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9564:                                 'Student '.$uname.' has multiple sheets',2);
                   9565:             next;
                   9566:         }
                   9567:         my $pid = $scan_record->{'scantron.ID'};
                   9568:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9569:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9570:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9571:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9572:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9573:2): 
                   9574:2):         my $scancode;
                   9575:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9576:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9577:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9578:2):         } else {
                   9579:2):             $scancode = '';
                   9580:2):         }
                   9581:2): 
                   9582:2):         my @mapresources = @resources;
          6(raebur 9583:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9584:3):         my %respnumlookup=();
                   9585:3):         my %startline=();
                   9586:3):         if ($randomorder || $randompick) {
          1(raebur 9587:2):             @mapresources =
          6(raebur 9588:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9589:3):                              \%orderedforcode);
                   9590:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9591:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9592:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9593:3):                                              \%respnumlookup,\%startline);
                   9594:3):             if ($randompick && $total) {
                   9595:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9596:3):             }
          1(raebur 9597:2):         }
          6(raebur 9598:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9599:3):         chomp($scandata{$pid});
                   9600:3):         $scandata{$pid} =~ s/\r$//;
                   9601:3): 
1.523     raeburn  9602:         my $counter = -1;
1.596.2.12.2.  1(raebur 9603:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9604:             my $parts;
1.554     raeburn  9605:             my $ressymb = $resource->symb();
1.557     raeburn  9606:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9607:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.596.2.12.2.  1(raebur 9608:7):                 my $currcode;
                   9609:7):                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9610:7):                     $currcode = $scancode;
                   9611:7):                 }
1.557     raeburn  9612:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9613:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9614:):                                               $username,$domain,undef,
          1(raebur 9615:7):                                               $bubbles_per_row,$currcode);
1.557     raeburn  9616:             } else {
                   9617:                 $parts = $grader_partids_by_symb{$ressymb};
                   9618:             }
1.542     raeburn  9619:             ($counter,my $recording) =
                   9620:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9621:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9622:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9623:3):                                          $randomorder,$randompick,
                   9624:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9625:             $record{$pid} .= $recording;
1.523     raeburn  9626:         }
                   9627:     }
                   9628:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9629:     $r->print('<br />');
                   9630:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9631:     $passed = 0;
                   9632:     $failed = 0;
                   9633:     $numstudents = 0;
                   9634:     foreach my $last (sort(keys(%bylast))) {
                   9635:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9636:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9637:                 my $showscandata = $scandata{$pid};
                   9638:                 my $showrecord = $record{$pid};
                   9639:                 $showscandata =~ s/\s/&nbsp;/g;
                   9640:                 $showrecord =~ s/\s/&nbsp;/g;
                   9641:                 if ($scandata{$pid} eq $record{$pid}) {
                   9642:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9643:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9644: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9645: '</tr>'."\n".
                   9646: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9647:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9648:                     $passed ++;
                   9649:                 } else {
                   9650:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9651:                     $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  9652: '</tr>'."\n".
                   9653: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9654:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9655: '</tr>'."\n";
                   9656:                     $failed ++;
                   9657:                 }
                   9658:                 $numstudents ++;
                   9659:             }
                   9660:         }
                   9661:     }
1.596.2.4  raeburn  9662:     $r->print('<p>'.
1.596.2.8  raeburn  9663:               &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  9664:                   '<b>',
                   9665:                   $numstudents,
                   9666:                   '</b>',
                   9667:                   $env{'form.scantron_maxbubble'}).
                   9668:               '</p>'
                   9669:     );
1.596.2.12.2.  2(raebur 9670:2):     $r->print('<p>'
                   9671:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9672:2):              .'<br />'
                   9673:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9674:2):              .'</p>');
1.523     raeburn  9675:     if ($passed) {
1.572     www      9676:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9677:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9678:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9679:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9680:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9681:                  $okstudents."\n".
                   9682:                  &Apache::loncommon::end_data_table().'<br />');
                   9683:     }
                   9684:     if ($failed) {
1.572     www      9685:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9686:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9687:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9688:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9689:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9690:                  $badstudents."\n".
                   9691:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9692:                  &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  9693:     }
1.596.2.12.2.  1(raebur 9694:0):     $r->print('</form><br />');
1.523     raeburn  9695:     return;
                   9696: }
                   9697: 
1.542     raeburn  9698: sub verify_scantron_grading {
1.554     raeburn  9699:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9700:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9701:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9702:     my ($record,%expected,%startpos);
                   9703:     return ($counter,$record) if (!ref($resource));
                   9704:     return ($counter,$record) if (!$resource->is_problem());
                   9705:     my $symb = $resource->symb();
1.554     raeburn  9706:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9707:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9708:         $counter ++;
                   9709:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9710:3):         my $respnum = $counter;
                   9711:3):         if ($randomorder || $randompick) {
                   9712:3):             $respnum = $respnumlookup->{$counter};
                   9713:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9714:3):         } else {
                   9715:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9716:3):         }
                   9717:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9718:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9719:             foreach my $item (@sub_lines) {
                   9720:                 $expected{$part_id} += $item;
                   9721:             }
                   9722:         } else {
1.596.2.12.2.  6(raebur 9723:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9724:         }
                   9725:     }
                   9726:     if ($symb) {
                   9727:         my %recorded;
                   9728:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9729:         if ($returnhash{'version'}) {
                   9730:             my %lasthash=();
                   9731:             my $version;
                   9732:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9733:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9734:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9735:                 }
                   9736:             }
                   9737:             foreach my $key (keys(%lasthash)) {
                   9738:                 if ($key =~ /\.scantron$/) {
                   9739:                     my $value = &unescape($lasthash{$key});
                   9740:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9741:                     if ($value eq '') {
                   9742:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9743:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9744:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9745:                             }
                   9746:                         }
                   9747:                     } else {
                   9748:                         my @tocheck;
                   9749:                         my @items = split(//,$value);
                   9750:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9751:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9752:                             if (@items < $expected{$part_id}) {
                   9753:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9754:                                 my @singles = split(//,$fragment);
                   9755:                                 foreach my $pos (@singles) {
                   9756:                                     if ($pos eq ' ') {
                   9757:                                         push(@tocheck,$pos);
                   9758:                                     } else {
                   9759:                                         my $next = shift(@items);
                   9760:                                         push(@tocheck,$next);
                   9761:                                     }
                   9762:                                 }
                   9763:                             } else {
                   9764:                                 @tocheck = @items;
                   9765:                             }
                   9766:                             foreach my $letter (@tocheck) {
                   9767:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9768:                                     if ($letter !~ /^[A-J]$/) {
                   9769:                                         $letter = $scantron_config->{'Qoff'};
                   9770:                                     }
                   9771:                                     $recorded{$part_id} .= $letter;
                   9772:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9773:                                     my $digit;
                   9774:                                     if ($letter !~ /^[A-J]$/) {
                   9775:                                         $digit = $scantron_config->{'Qoff'};
                   9776:                                     } else {
                   9777:                                         $digit = $lettdig->{$letter};
                   9778:                                     }
                   9779:                                     $recorded{$part_id} .= $digit;
                   9780:                                 }
                   9781:                             }
                   9782:                         } else {
                   9783:                             @tocheck = @items;
                   9784:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9785:                                 my $curr_sub = shift(@tocheck);
                   9786:                                 my $digit;
                   9787:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9788:                                     $digit = $lettdig->{$curr_sub}-1;
                   9789:                                 }
                   9790:                                 if ($curr_sub eq 'J') {
                   9791:                                     $digit += scalar($numletts);
                   9792:                                 }
                   9793:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9794:                                     if ($j == $digit) {
                   9795:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9796:                                     } else {
                   9797:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9798:                                     }
                   9799:                                 }
                   9800:                             }
                   9801:                         }
                   9802:                     }
                   9803:                 }
                   9804:             }
                   9805:         }
1.554     raeburn  9806:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9807:             if ($recorded{$part_id} eq '') {
                   9808:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9809:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9810:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9811:                     }
                   9812:                 }
                   9813:             }
                   9814:             $record .= $recorded{$part_id};
                   9815:         }
                   9816:     }
                   9817:     return ($counter,$record);
                   9818: }
                   9819: 
1.75      albertel 9820: #-------- end of section for handling grading scantron forms -------
                   9821: #
                   9822: #-------------------------------------------------------------------
                   9823: 
1.72      ng       9824: #-------------------------- Menu interface -------------------------
                   9825: #
1.596.2.12.2.  (raeburn 9826:): #--- Href with symb and command ---
                   9827:): 
                   9828:): sub href_symb_cmd {
                   9829:):     my ($symb,$cmd)=@_;
                   9830:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9831:): }
                   9832:): 
1.443     banghart 9833: sub grading_menu {
1.596.2.12.2.  1(raebur 9834:0):     my ($request,$symb) = @_;
1.443     banghart 9835:     if (!$symb) {return '';}
                   9836: 
                   9837:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.596.2.12.2.  1(raebur 9838:0):                   'command'=>'individual');
                   9839:0): 
                   9840:0):     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9841:0): 
                   9842:0):     $fields{'command'}='ungraded';
                   9843:0):     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9844:0): 
                   9845:0):     $fields{'command'}='table';
                   9846:0):     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9847:0): 
                   9848:0):     $fields{'command'}='all_for_one';
                   9849:0):     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9850:0): 
                   9851:0):     $fields{'command'}='downloadfilesselect';
                   9852:0):     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9853:     
1.443     banghart 9854:     $fields{'command'} = 'csvform';
1.538     schulted 9855:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9856:     
1.443     banghart 9857:     $fields{'command'} = 'processclicker';
1.538     schulted 9858:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9859:     
1.443     banghart 9860:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9861:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.596.2.12.2.  1(raebur 9862:0): 
                   9863:0):     $fields{'command'} = 'initialverifyreceipt';
                   9864:0):     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9865:     
1.596.2.12.2.  1(raebur 9866:0):     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9867:             items =>[
1.596.2.12.2.  1(raebur 9868:0):                         {       linktext => 'Select individual students to grade',
                   9869:0):                                 url => $url1a,
                   9870:0):                                 permission => 'F',
                   9871:0):                                 icon => 'grade_students.png',
                   9872:0):                                 linktitle => 'Grade current resource for a selection of students.'
                   9873:0):                         },
                   9874:0):                         {       linktext => 'Grade ungraded submissions',
                   9875:0):                                 url => $url1b,
                   9876:0):                                 permission => 'F',
                   9877:0):                                 icon => 'ungrade_sub.png',
                   9878:0):                                 linktitle => 'Grade all submissions that have not been graded yet.'
                   9879:0):                         },
                   9880:0): 
                   9881:0):                         {       linktext => 'Grading table',
                   9882:0):                                 url => $url1c,
                   9883:0):                                 permission => 'F',
                   9884:0):                                 icon => 'grading_table.png',
                   9885:0):                                 linktitle => 'Grade current resource for all students.'
                   9886:0):                         },
                   9887:0):                         {       linktext => 'Grade page/folder for one student',
                   9888:0):                                 url => $url1d,
                   9889:0):                                 permission => 'F',
                   9890:0):                                 icon => 'grade_PageFolder.png',
                   9891:0):                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.538     schulted 9892:                         },
1.596.2.12.2.  1(raebur 9893:0):                         {       linktext => 'Download submissions',
                   9894:0):                                 url => $url1e,
                   9895:0):                                 permission => 'F',
                   9896:0):                                 icon => 'download_sub.png',
                   9897:0):                                 linktitle => 'Download all students submissions.'
                   9898:0):                         }]},
                   9899:0):                          { categorytitle=>'Automated Grading',
                   9900:0):                items =>[
                   9901:0): 
1.538     schulted 9902:                 	    {	linktext => 'Upload Scores',
                   9903:                     		url => $url2,
                   9904:                     		permission => 'F',
                   9905:                     		icon => 'uploadscores.png',
                   9906:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9907:                 	    },
                   9908:                 	    {	linktext => 'Process Clicker',
                   9909:                     		url => $url3,
                   9910:                     		permission => 'F',
                   9911:                     		icon => 'addClickerInfoFile.png',
                   9912:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9913:                 	    },
1.587     raeburn  9914:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9915:                     		url => $url4,
                   9916:                     		permission => 'F',
1.596.2.12.2.  1(raebur 9917:0):                     		icon => 'bubblesheet.png',
1.596.2.4  raeburn  9918:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.596.2.12.2.  1(raebur 9919:0):                 	    },
                   9920:0):                             {   linktext => 'Verify Receipt Number',
                   9921:0):                                 url => $url5,
                   9922:0):                                 permission => 'F',
                   9923:0):                                 icon => 'receipt_number.png',
                   9924:0):                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9925:0):                             }
                   9926:0): 
1.538     schulted 9927:                     ]
                   9928:             });
                   9929: 
1.443     banghart 9930:     # Create the menu
                   9931:     my $Str;
1.445     banghart 9932:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9933:     $Str .= '<input type="hidden" name="command" value="" />'.
1.596.2.12.2.  1(raebur 9934:0):     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.443     banghart 9935: 
1.596.2.12.2.  1(raebur 9936:0):     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9937:     return $Str;    
                   9938: }
                   9939: 
1.596.2.12.2.  1(raebur 9940:0): sub ungraded {
                   9941:0):     my ($request)=@_;
                   9942:0):     &submit_options($request);
                   9943:0): }
1.443     banghart 9944: 
1.596.2.12.2.  1(raebur 9945:0): sub submit_options_sequence {
                   9946:0):     my ($request,$symb) = @_;
1.72      ng       9947:     if (!$symb) {return '';}
1.596.2.12.2.  1(raebur 9948:0):     &commonJSfunctions($request);
                   9949:0):     my $result;
1.72      ng       9950: 
1.596.2.12.2.  1(raebur 9951:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9952:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9953:0):     $result.=&selectfield(0).
                   9954:0):             '<input type="hidden" name="command" value="pickStudentPage" />
                   9955:0):             <div>
                   9956:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9957:0):             </div>
                   9958:0):         </div>
                   9959:0):   </form>';
                   9960:0):     return $result;
                   9961:0): }
                   9962:0): 
                   9963:0): sub submit_options_table {
                   9964:0):     my ($request,$symb) = @_;
                   9965:0):     if (!$symb) {return '';}
1.118     ng       9966:     &commonJSfunctions($request);
1.473     albertel 9967:     my $result;
1.596.2.12.2.  1(raebur 9968:0): 
                   9969:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9970:0):         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9971:0): 
                   9972:0):     $result.=&selectfield(1).
                   9973:0):             '<input type="hidden" name="command" value="viewgrades" />
                   9974:0):             <div>
                   9975:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9976:0):             </div>
                   9977:0):         </div>
                   9978:0):   </form>';
                   9979:0):     return $result;
                   9980:0): }
                   9981:0): 
                   9982:0): sub submit_options_download {
                   9983:0):     my ($request,$symb) = @_;
                   9984:0):     if (!$symb) {return '';}
                   9985:0): 
                   9986:0):     my $res_error;
                   9987:0):     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
                   9988:0):         &response_type($symb,\$res_error);
                   9989:0):     if ($res_error) {
                   9990:0):         $request->print(&mt('An error occurred retrieving response types'));
                   9991:0):         return;
                   9992:0):     }
                   9993:0):     unless ($numessay) {
                   9994:0):         $request->print(&mt('No essayresponse items found'));
                   9995:0):         return;
                   9996:0):     }
                   9997:0):     my $table;
                   9998:0):     if (ref($partlist) eq 'ARRAY') {
                   9999:0):         if (scalar(@$partlist) > 1 ) {
                   10000:0):             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
1.533     bisitz   10001:         }
                   10002:     }
                   10003: 
1.596.2.12.2.  1(raebur 10004:0):     &commonJSfunctions($request);
1.72      ng       10005: 
1.596.2.12.2.  1(raebur 10006:0):     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10007:0):         $table."\n".
                   10008:0):         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 10009:     $result.='
1.533     bisitz   10010: <h2>
1.596.2.12.2.  1(raebur 10011:0):   '.&mt('Select Students for whom to Download Submissions').'
                   10012:0): </h2>'.&selectfield(1).'
                   10013:0):                 <input type="hidden" name="command" value="downloadfileslink" />
                   10014:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10015:0):             </div>
                   10016:0):           </div>
                   10017:0): 
                   10018:0): 
                   10019:0):   </form>';
                   10020:0):     return $result;
                   10021:0): }
                   10022:0): 
                   10023:0): #--- Displays the submissions first page -------
                   10024:0): sub submit_options {
                   10025:0):     my ($request,$symb) = @_;
                   10026:0):     if (!$symb) {return '';}
                   10027:0): 
                   10028:0):     &commonJSfunctions($request);
                   10029:0):     my $result;
                   10030:0): 
                   10031:0):     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10032:0): 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10033:0):     $result.=&selectfield(1).'
                   10034:0):                 <input type="hidden" name="command" value="submission" />
                   10035:0):               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10036:0):             </div>
                   10037:0):           </div>
                   10038:0):   </form>';
                   10039:0):     return $result;
                   10040:0): }
                   10041:0): 
                   10042:0): sub selectfield {
                   10043:0):    my ($full)=@_;
                   10044:0):    my %options =
                   10045:0):        (&substatus_options,
                   10046:0):         'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10047:0):    my $result='<div class="LC_columnSection">
1.533     bisitz   10048: 
                   10049:     <fieldset>
                   10050:       <legend>
                   10051:        '.&mt('Sections').'
                   10052:       </legend>
1.596.2.12.2.  1(raebur 10053:0):       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10054:     </fieldset>
1.596.2.12.2.  1(raebur 10055:0): 
1.533     bisitz   10056:     <fieldset>
                   10057:       <legend>
                   10058:         '.&mt('Groups').'
                   10059:       </legend>
                   10060:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10061:     </fieldset>
1.596.2.12.2.  1(raebur 10062:0):  
1.533     bisitz   10063:     <fieldset>
                   10064:       <legend>
                   10065:         '.&mt('Access Status').'
                   10066:       </legend>
1.596.2.12.2.  1(raebur 10067:0):       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10068:0):     </fieldset>';
                   10069:0):     if ($full) {
                   10070:0):         $result.='
1.533     bisitz   10071:     <fieldset>
                   10072:       <legend>
                   10073:         '.&mt('Submission Status').'
1.596.2.12.2.  1(raebur 10074:0):       </legend>'.
                   10075:0):        &Apache::loncommon::select_form('all','submitonly',\%options).
                   10076:0):    '</fieldset>';
                   10077:0):     }
                   10078:0):     $result.='</div><br />';
1.44      ng       10079:     return $result;
1.2       albertel 10080: }
                   10081: 
1.596.2.12.2.  7(raebur 10082:6): sub substatus_options {
                   10083:6):     return &Apache::lonlocal::texthash(
                   10084:6):                                       'yes'       => 'with submissions',
                   10085:6):                                       'queued'    => 'in grading queue',
                   10086:6):                                       'graded'    => 'with ungraded submissions',
                   10087:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10088:7):                                       'all'       => 'with any status',
                   10089:7):                                       );
          7(raebur 10090:6): }
                   10091:6): 
          1(raebur 10092:0): sub transtatus_options {
                   10093:0):     return &Apache::lonlocal::texthash(
                   10094:0):                                        'yes'       => 'with score transactions',
                   10095:0):                                        'incorrect' => 'with less than full credit',
                   10096:0):                                        'all'       => 'with any status',
                   10097:0):                                       );
                   10098:0): }
                   10099:0): 
1.285     albertel 10100: sub reset_perm {
                   10101:     undef(%perm);
                   10102: }
                   10103: 
                   10104: sub init_perm {
                   10105:     &reset_perm();
1.300     albertel 10106:     foreach my $test_perm ('vgr','mgr','opa') {
                   10107: 
                   10108: 	my $scope = $env{'request.course.id'};
                   10109: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10110: 
                   10111: 	    $scope .= '/'.$env{'request.course.sec'};
                   10112: 	    if ( $perm{$test_perm}=
                   10113: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10114: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10115: 	    } else {
                   10116: 		delete($perm{$test_perm});
                   10117: 	    }
1.285     albertel 10118: 	}
                   10119:     }
                   10120: }
                   10121: 
1.596.2.12.2.  (raeburn 10122:): sub init_old_essays {
                   10123:):     my ($symb,$apath,$adom,$aname) = @_;
                   10124:):     if ($symb ne '') {
                   10125:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10126:):         if (keys(%essays) > 0) {
                   10127:):             $old_essays{$symb} = \%essays;
                   10128:):         }
                   10129:):     }
                   10130:):     return;
                   10131:): }
                   10132:): 
                   10133:): sub reset_old_essays {
                   10134:):     undef(%old_essays);
                   10135:): }
                   10136:): 
1.400     www      10137: sub gather_clicker_ids {
1.408     albertel 10138:     my %clicker_ids;
1.400     www      10139: 
                   10140:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10141: 
                   10142:     # Set up a couple variables.
1.407     albertel 10143:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10144:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10145:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10146: 
1.407     albertel 10147:     foreach my $student (keys(%$classlist)) {
1.438     www      10148:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10149:         my $username = $classlist->{$student}->[$username_idx];
                   10150:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10151:         my $clickers =
1.408     albertel 10152: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10153:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10154:             $id=~s/^[\#0]+//;
1.421     www      10155:             $id=~s/[\-\:]//g;
1.407     albertel 10156:             if (exists($clicker_ids{$id})) {
1.408     albertel 10157: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10158:             } else {
1.408     albertel 10159: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10160:             }
                   10161:         }
                   10162:     }
1.407     albertel 10163:     return %clicker_ids;
1.400     www      10164: }
                   10165: 
1.402     www      10166: sub gather_adv_clicker_ids {
1.408     albertel 10167:     my %clicker_ids;
1.402     www      10168:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10169:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10170:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10171:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10172:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10173:             my ($puname,$pudom)=split(/\:/,$person);
                   10174:             my $clickers =
1.408     albertel 10175: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10176:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10177: 		$id=~s/^[\#0]+//;
1.421     www      10178:                 $id=~s/[\-\:]//g;
1.408     albertel 10179: 		if (exists($clicker_ids{$id})) {
                   10180: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10181: 		} else {
                   10182: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10183: 		}
1.405     www      10184:             }
1.402     www      10185:         }
                   10186:     }
1.407     albertel 10187:     return %clicker_ids;
1.402     www      10188: }
                   10189: 
1.413     www      10190: sub clicker_grading_parameters {
                   10191:     return ('gradingmechanism' => 'scalar',
                   10192:             'upfiletype' => 'scalar',
                   10193:             'specificid' => 'scalar',
                   10194:             'pcorrect' => 'scalar',
                   10195:             'pincorrect' => 'scalar');
                   10196: }
                   10197: 
1.400     www      10198: sub process_clicker {
1.596.2.12.2.  1(raebur 10199:0):     my ($r,$symb)=@_;
1.400     www      10200:     if (!$symb) {return '';}
                   10201:     my $result=&checkforfile_js();
1.596.2.12.2.  1(raebur 10202:0):     $result.=&Apache::loncommon::start_data_table().
                   10203:0):              &Apache::loncommon::start_data_table_header_row().
                   10204:0):              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10205:0):              &Apache::loncommon::end_data_table_header_row().
                   10206:0):              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10207: # Attempt to restore parameters from last session, set defaults if not present
                   10208:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10209:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10210:                                                  \%Saveable_Parameters);
                   10211:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10212:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10213:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10214:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10215: 
                   10216:     my %checked;
1.521     www      10217:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10218:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10219:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10220:        }
                   10221:     }
                   10222: 
1.596.2.12.2.  1(raebur 10223:0):     my $upload=&mt("Evaluate File");
1.400     www      10224:     my $type=&mt("Type");
1.402     www      10225:     my $attendance=&mt("Award points just for participation");
                   10226:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10227:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10228:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10229:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10230:     my $pcorrect=&mt("Percentage points for correct solution");
                   10231:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10232:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10233:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10234:):                                                     'interwrite' => 'interwrite PRS',
                   10235:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10236:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10237:0):     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10238: function sanitycheck() {
                   10239: // Accept only integer percentages
                   10240:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10241:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10242: // Find out grading choice
                   10243:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10244:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10245:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10246:       }
                   10247:    }
                   10248: // By default, new choice equals user selection
                   10249:    newgradingchoice=gradingchoice;
                   10250: // Not good to give more points for false answers than correct ones
                   10251:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10252:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10253:    }
                   10254: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10255:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10256:       document.forms.gradesupload.pcorrect.value=100;
                   10257:       document.forms.gradesupload.pincorrect.value=100;
                   10258:    }
                   10259: // If the values are different, cannot be attendance only
                   10260:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10261:        (gradingchoice=='attendance')) {
                   10262:        newgradingchoice='personnel';
                   10263:    }
                   10264: // Change grading choice to new one
                   10265:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10266:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10267:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10268:       } else {
                   10269:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10270:       }
                   10271:    }
                   10272: // Remember the old state
                   10273:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10274: }
1.596.2.12.2.  1(raebur 10275:0): ENDUPFORM
                   10276:0):     $result.= <<ENDUPFORM;
1.400     www      10277: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10278: <input type="hidden" name="symb" value="$symb" />
                   10279: <input type="hidden" name="command" value="processclickerfile" />
                   10280: <input type="file" name="upfile" size="50" />
                   10281: <br /><label>$type: $selectform</label>
1.596.2.12.2.  1(raebur 10282:0): ENDUPFORM
                   10283:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10284:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10285:0):       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10286: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10287: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10288: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10289: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10290: <br />&nbsp;&nbsp;&nbsp;
                   10291: <input type="text" name="givenanswer" size="50" />
1.413     www      10292: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.596.2.12.2.  1(raebur 10293:0): ENDGRADINGFORM
                   10294:0):     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10295:0):                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10296:0):       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10297: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10298: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10299: </form>
1.596.2.12.2.  1(raebur 10300:0): ENDPERCFORM
                   10301:0):     $result.='</td>'.
                   10302:0):              &Apache::loncommon::end_data_table_row().
                   10303:0):              &Apache::loncommon::end_data_table();
1.400     www      10304:     return $result;
                   10305: }
                   10306: 
                   10307: sub process_clicker_file {
1.596.2.12.2.  1(raebur 10308:0):     my ($r,$symb) = @_;
1.400     www      10309:     if (!$symb) {return '';}
1.413     www      10310: 
                   10311:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10312:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10313:                                               \%Saveable_Parameters);
1.596.2.12.2.  1(raebur 10314:0):     my $result='';
1.404     www      10315:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10316: 	$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 10317:0): 	return $result;
1.404     www      10318:     }
1.522     www      10319:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10320:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.596.2.12.2.  1(raebur 10321:0):         return $result;
1.521     www      10322:     }
1.522     www      10323:     my $foundgiven=0;
1.521     www      10324:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10325:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10326:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10327:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10328:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10329:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10330:         $foundgiven=$#answers+1;
1.521     www      10331:     }
1.407     albertel 10332:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10333:     my %correct_ids;
1.404     www      10334:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10335: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10336:     }
                   10337:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10338: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10339: 	   $correct_id=~tr/a-z/A-Z/;
                   10340: 	   $correct_id=~s/\s//gs;
                   10341: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10342:            $correct_id=~s/[\-\:]//g;
1.414     www      10343:            if ($correct_id) {
                   10344: 	      $correct_ids{$correct_id}='specified';
                   10345:            }
                   10346:         }
1.400     www      10347:     }
1.404     www      10348:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10349: 	$result.=&mt('Score based on attendance only');
1.521     www      10350:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10351:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10352:     } else {
1.408     albertel 10353: 	my $number=0;
1.411     www      10354: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10355: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10356: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10357: 	    if ($correct_ids{$id} eq 'specified') {
                   10358: 		$result.=&mt('specified');
                   10359: 	    } else {
                   10360: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10361: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10362: 	    }
                   10363: 	    $number++;
                   10364: 	}
1.411     www      10365:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10366:3):         if ($number==0) {
                   10367:3):             $result .=
                   10368:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10369:3):                      &mt('No IDs found to determine correct answer'),1);
          1(raebur 10370:0):             return $result;
          5(raebur 10371:3):         }
1.404     www      10372:     }
1.405     www      10373:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10374:3):         $result .=
                   10375:3):             &Apache::lonhtmlcommon::confirm_success(
                   10376:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10377:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
          1(raebur 10378:0):         return $result;
1.405     www      10379:     }
1.596.2.12.2.  7(raebur 10380:9):     my $mimetype;
                   10381:9):     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10382:9):         my $mm = new File::MMagic;
                   10383:9):         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10384:9):         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10385:9):             $result.= '<p>'.
                   10386:9):                 &Apache::lonhtmlcommon::confirm_success(
                   10387:9):                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
          1(raebur 10388:0):             return $result;
          7(raebur 10389:9):         }
                   10390:9):     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10391:9):         $result .= '<p>'.
                   10392:9):             &Apache::lonhtmlcommon::confirm_success(
                   10393:9):                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
          1(raebur 10394:0):         return $result;
          7(raebur 10395:9):     }
1.410     www      10396: 
                   10397: # Were able to get all the info needed, now analyze the file
                   10398: 
1.411     www      10399:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10400:     $symb = &Apache::lonenc::check_encrypt($symb);
1.596.2.12.2.  1(raebur 10401:0):     $result.=&Apache::loncommon::start_data_table().
                   10402:0):              &Apache::loncommon::start_data_table_header_row().
                   10403:0):              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10404:0):              &Apache::loncommon::end_data_table_header_row().
                   10405:0):              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10406:0): <td>
1.410     www      10407: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10408: <input type="hidden" name="symb" value="$symb" />
                   10409: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10410: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10411: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10412: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10413: ENDHEADER
1.522     www      10414:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10415:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10416:     } 
1.408     albertel 10417:     my %responses;
                   10418:     my @questiontitles;
1.405     www      10419:     my $errormsg='';
                   10420:     my $number=0;
                   10421:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.596.2.12.2.  7(raebur 10422:9):         if ($mimetype eq 'text/plain') {
                   10423:9):             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10424:9):         } elsif ($mimetype eq 'text/html') {
                   10425:9):             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10426:9):         }
                   10427:9):     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10428:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.596.2.12.2.  7(raebur 10429:9):     } elsif ($env{'form.upfiletype'} eq 'turning') {
          (raeburn 10430:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10431:):     }
1.411     www      10432:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10433:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10434:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10435:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10436:              '<br />';
1.522     www      10437:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10438:        $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 10439:0):        return $result;
1.522     www      10440:     } 
1.414     www      10441: # Remember Question Titles
                   10442: # FIXME: Possibly need delimiter other than ":"
                   10443:     for (my $i=0;$i<$number;$i++) {
                   10444:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10445:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10446:     }
1.411     www      10447:     my $correct_count=0;
                   10448:     my $student_count=0;
                   10449:     my $unknown_count=0;
1.414     www      10450: # Match answers with usernames
                   10451: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10452:     foreach my $id (keys(%responses)) {
1.410     www      10453:        if ($correct_ids{$id}) {
1.414     www      10454:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10455:           $correct_count++;
1.410     www      10456:        } elsif ($clicker_ids{$id}) {
1.437     www      10457:           if ($clicker_ids{$id}=~/\,/) {
                   10458: # More than one user with the same clicker!
1.596.2.12.2.  1(raebur 10459:0):              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10460:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10461:0):                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10462:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10463:                            "<select name='multi".$id."'>";
                   10464:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10465:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10466:              }
                   10467:              $result.='</select>';
                   10468:              $unknown_count++;
                   10469:           } else {
                   10470: # Good: found one and only one user with the right clicker
                   10471:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10472:              $student_count++;
                   10473:           }
1.410     www      10474:        } else {
1.596.2.12.2.  1(raebur 10475:0):           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10476:0):                            &Apache::loncommon::start_data_table_row()."<td>".
                   10477:0):                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10478:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10479:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10480:                    "\n".&mt("Domain").": ".
                   10481:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.12.2.  0(raebur 10482:0):                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10483:           $unknown_count++;
1.410     www      10484:        }
1.405     www      10485:     }
1.412     www      10486:     $result.='<hr />'.
                   10487:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10488:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10489:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10490:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10491:        } elsif ($correct_count>1) {
1.414     www      10492:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10493:        }
                   10494:     }
1.428     www      10495:     if ($number<1) {
                   10496:        $errormsg.="Found no questions.";
                   10497:     }
1.412     www      10498:     if ($errormsg) {
                   10499:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10500:     } else {
                   10501:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10502:     }
1.596.2.12.2.  1(raebur 10503:0):     $result.='</form></td>'.
                   10504:0):              &Apache::loncommon::end_data_table_row().
                   10505:0):              &Apache::loncommon::end_data_table();
                   10506:0):     return $result;
1.400     www      10507: }
                   10508: 
1.405     www      10509: sub iclicker_eval {
1.406     www      10510:     my ($questiontitles,$responses)=@_;
1.405     www      10511:     my $number=0;
                   10512:     my $errormsg='';
                   10513:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10514:         my %components=&Apache::loncommon::record_sep($line);
                   10515:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10516: 	if ($entries[0] eq 'Question') {
                   10517: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10518: 		$$questiontitles[$number]=$entries[$i];
                   10519: 		$number++;
                   10520: 	    }
                   10521: 	}
                   10522: 	if ($entries[0]=~/^\#/) {
                   10523: 	    my $id=$entries[0];
                   10524: 	    my @idresponses;
                   10525: 	    $id=~s/^[\#0]+//;
                   10526: 	    for (my $i=0;$i<$number;$i++) {
                   10527: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10528:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10529: 		push(@idresponses,$entries[$idx]);
                   10530: 	    }
                   10531: 	    $$responses{$id}=join(',',@idresponses);
                   10532: 	}
1.405     www      10533:     }
                   10534:     return ($errormsg,$number);
                   10535: }
                   10536: 
1.596.2.12.2.  7(raebur 10537:9): sub iclickerxml_eval {
                   10538:9):     my ($questiontitles,$responses)=@_;
                   10539:9):     my $number=0;
                   10540:9):     my $errormsg='';
                   10541:9):     my @state;
                   10542:9):     my %respbyid;
                   10543:9):     my $p = HTML::Parser->new
                   10544:9):     (
                   10545:9):         xml_mode => 1,
                   10546:9):         start_h =>
                   10547:9):             [sub {
                   10548:9):                  my ($tagname,$attr) = @_;
                   10549:9):                  push(@state,$tagname);
                   10550:9):                  if ("@state" eq "ssn p") {
                   10551:9):                      my $title = $attr->{qn};
                   10552:9):                      $title =~ s/(^\s+|\s+$)//g;
                   10553:9):                      $questiontitles->[$number]=$title;
                   10554:9):                  } elsif ("@state" eq "ssn p v") {
                   10555:9):                      my $id = $attr->{id};
                   10556:9):                      my $entry = $attr->{ans};
                   10557:9):                      $id=~s/^[\#0]+//;
                   10558:9):                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10559:9):                      $respbyid{$id}[$number] = $entry;
                   10560:9):                  }
                   10561:9):             }, "tagname, attr"],
                   10562:9):          end_h =>
                   10563:9):                [sub {
                   10564:9):                    my ($tagname) = @_;
                   10565:9):                    if ("@state" eq "ssn p") {
                   10566:9):                        $number++;
                   10567:9):                    }
                   10568:9):                    pop(@state);
                   10569:9):                 }, "tagname"],
                   10570:9):     );
                   10571:9): 
                   10572:9):     $p->parse($env{'form.upfile'});
                   10573:9):     $p->eof;
                   10574:9):     foreach my $id (keys(%respbyid)) {
                   10575:9):         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10576:9):     }
                   10577:9):     return ($errormsg,$number);
                   10578:9): }
                   10579:9): 
1.419     www      10580: sub interwrite_eval {
                   10581:     my ($questiontitles,$responses)=@_;
                   10582:     my $number=0;
                   10583:     my $errormsg='';
1.420     www      10584:     my $skipline=1;
                   10585:     my $questionnumber=0;
                   10586:     my %idresponses=();
1.419     www      10587:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10588:         my %components=&Apache::loncommon::record_sep($line);
                   10589:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10590:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10591:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10592:         next if $skipline;
                   10593:         if ($entries[0]!=$questionnumber) {
                   10594:            $questionnumber=$entries[0];
                   10595:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10596:            $number++;
1.419     www      10597:         }
1.420     www      10598:         my $id=$entries[4];
                   10599:         $id=~s/^[\#0]+//;
1.421     www      10600:         $id=~s/^v\d*\://i;
                   10601:         $id=~s/[\-\:]//g;
1.420     www      10602:         $idresponses{$id}[$number]=$entries[6];
                   10603:     }
1.524     raeburn  10604:     foreach my $id (keys(%idresponses)) {
1.420     www      10605:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10606:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10607:     }
                   10608:     return ($errormsg,$number);
                   10609: }
                   10610: 
1.596.2.12.2.  (raeburn 10611:): sub turning_eval {
                   10612:):     my ($questiontitles,$responses)=@_;
                   10613:):     my $number=0;
                   10614:):     my $errormsg='';
                   10615:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10616:):         my %components=&Apache::loncommon::record_sep($line);
                   10617:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10618:):         if ($#entries>$number) { $number=$#entries; }
                   10619:):         my $id=$entries[0];
                   10620:):         my @idresponses;
                   10621:):         $id=~s/^[\#0]+//;
                   10622:):         unless ($id) { next; }
                   10623:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10624:):             $entries[$idx]=~s/\,/\;/g;
                   10625:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10626:):             push(@idresponses,$entries[$idx]);
                   10627:):         }
                   10628:):         $$responses{$id}=join(',',@idresponses);
                   10629:):     }
                   10630:):     for (my $i=1; $i<=$number; $i++) {
                   10631:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10632:):     }
                   10633:):     return ($errormsg,$number);
                   10634:): }
                   10635:): 
1.414     www      10636: sub assign_clicker_grades {
1.596.2.12.2.  1(raebur 10637:0):     my ($r,$symb) = @_;
1.414     www      10638:     if (!$symb) {return '';}
1.416     www      10639: # See which part we are saving to
1.582     raeburn  10640:     my $res_error;
                   10641:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10642:     if ($res_error) {
                   10643:         return &navmap_errormsg();
                   10644:     }
1.416     www      10645: # FIXME: This should probably look for the first handgradeable part
                   10646:     my $part=$$partlist[0];
                   10647: # Start screen output
1.596.2.12.2.  1(raebur 10648:0):     my $result = &Apache::loncommon::start_data_table(). 
                   10649:0):                  &Apache::loncommon::start_data_table_header_row().
                   10650:0):                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10651:0):                  &Apache::loncommon::end_data_table_header_row().
                   10652:0):                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10653: # Get correct result
                   10654: # FIXME: Possibly need delimiter other than ":"
                   10655:     my @correct=();
1.415     www      10656:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10657:     my $number=$env{'form.number'};
                   10658:     if ($gradingmechanism ne 'attendance') {
1.414     www      10659:        foreach my $key (keys(%env)) {
                   10660:           if ($key=~/^form\.correct\:/) {
                   10661:              my @input=split(/\,/,$env{$key});
                   10662:              for (my $i=0;$i<=$#input;$i++) {
                   10663:                  if (($correct[$i]) && ($input[$i]) &&
                   10664:                      ($correct[$i] ne $input[$i])) {
                   10665:                     $result.='<br /><span class="LC_warning">'.
                   10666:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10667:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10668:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10669:                     $correct[$i]=$input[$i];
                   10670:                  }
                   10671:              }
                   10672:           }
                   10673:        }
1.415     www      10674:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10675:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10676:              $result.='<br /><span class="LC_error">'.
                   10677:                       &mt('No correct result given for question "[_1]"!',
                   10678:                           $env{'form.question:'.$i}).'</span>';
                   10679:           }
                   10680:        }
1.596.2.4  raeburn  10681:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10682:     }
                   10683: # Start grading
1.415     www      10684:     my $pcorrect=$env{'form.pcorrect'};
                   10685:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10686:     my $storecount=0;
1.596.2.4  raeburn  10687:     my %users=();
1.415     www      10688:     foreach my $key (keys(%env)) {
1.420     www      10689:        my $user='';
1.415     www      10690:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10691:           $user=$1;
                   10692:        }
                   10693:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10694:           my $id=$1;
                   10695:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10696:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10697:           } elsif ($env{'form.multi'.$id}) {
                   10698:              $user=$env{'form.multi'.$id};
1.420     www      10699:           }
                   10700:        }
1.596.2.4  raeburn  10701:        if ($user) {
                   10702:           if ($users{$user}) {
                   10703:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10704:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10705:                       '</span><br />';
                   10706:           }
                   10707:           $users{$user}=1;
1.415     www      10708:           my @answer=split(/\,/,$env{$key});
                   10709:           my $sum=0;
1.522     www      10710:           my $realnumber=$number;
1.415     www      10711:           for (my $i=0;$i<$number;$i++) {
1.576     www      10712:              if  ($correct[$i] eq '-') {
                   10713:                 $realnumber--;
1.596.2.12.2.  1(raebur 10714:0):              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      10715:                 if ($gradingmechanism eq 'attendance') {
                   10716:                    $sum+=$pcorrect;
1.576     www      10717:                 } elsif ($correct[$i] eq '*') {
1.522     www      10718:                    $sum+=$pcorrect;
1.415     www      10719:                 } else {
1.596.2.4  raeburn  10720: # We actually grade if correct or not
                   10721:                    my $increment=$pincorrect;
                   10722: # Special case: numerical answer "0"
                   10723:                    if ($correct[$i] eq '0') {
                   10724:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10725:                          $increment=$pcorrect;
                   10726:                       }
                   10727: # General numerical answer, both evaluate to something non-zero
                   10728:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10729:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10730:                          $increment=$pcorrect;
                   10731:                       }
                   10732: # Must be just alphanumeric
                   10733:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10734:                       $increment=$pcorrect;
1.415     www      10735:                    }
1.596.2.4  raeburn  10736:                    $sum+=$increment;
1.415     www      10737:                 }
                   10738:              }
                   10739:           }
1.522     www      10740:           my $ave=$sum/(100*$realnumber);
1.416     www      10741: # Store
                   10742:           my ($username,$domain)=split(/\:/,$user);
                   10743:           my %grades=();
                   10744:           $grades{"resource.$part.solved"}='correct_by_override';
                   10745:           $grades{"resource.$part.awarded"}=$ave;
                   10746:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10747:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10748:                                                  $env{'request.course.id'},
                   10749:                                                  $domain,$username);
                   10750:           if ($returncode ne 'ok') {
                   10751:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10752:           } else {
                   10753:              $storecount++;
                   10754:           }
1.415     www      10755:        }
                   10756:     }
                   10757: # We are done
1.549     hauer    10758:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10759:              '</td>'.
                   10760:              &Apache::loncommon::end_data_table_row().
1.596.2.12.2.  1(raebur 10761:0):              &Apache::loncommon::end_data_table();
                   10762:0):     return $result;
1.414     www      10763: }
                   10764: 
1.582     raeburn  10765: sub navmap_errormsg {
                   10766:     return '<div class="LC_error">'.
                   10767:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10768:            &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  10769:            '</div>';
                   10770: }
                   10771: 
1.596.2.12.2.  (raeburn 10772:): sub startpage {
          1(raebur 10773:0):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
          9(raebur 10774:9):     my %args;
                   10775:9):     if ($onload) {
                   10776:9):          my %loaditems = (
                   10777:9):                         'onload' => $onload,
                   10778:9):                       );
                   10779:9):          $args{'add_entries'} = \%loaditems;
                   10780:9):     }
          (raeburn 10781:):     if ($nomenu) {
          9(raebur 10782:9):         $args{'only_body'} = 1;
                   10783:9):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
          (raeburn 10784:):     } else {
          1(raebur 10785:0):         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
          9(raebur 10786:9):         $args{'bread_crumbs'} = $crumbs;
                   10787:9):         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
          (raeburn 10788:):     }
                   10789:):     unless ($nodisplayflag) {
          1(raebur 10790:0):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
          (raeburn 10791:):     }
                   10792:): }
                   10793:): 
          1(raebur 10794:0): sub select_problem {
                   10795:0):     my ($r)=@_;
                   10796:0):     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
                   10797:0):     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1));
                   10798:0):     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10799:0):     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10800:0): }
                   10801:0): 
1.1       albertel 10802: sub handler {
1.41      ng       10803:     my $request=$_[0];
1.434     albertel 10804:     &reset_caches();
1.596.2.4  raeburn  10805:     if ($request->header_only) {
                   10806:         &Apache::loncommon::content_type($request,'text/html');
                   10807:         $request->send_http_header;
                   10808:         return OK;
1.41      ng       10809:     }
                   10810:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10811: 
1.596.2.12.2.  1(raebur 10812:0): # see what command we need to execute
                   10813:0):  
1.160     albertel 10814:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10815:     my $command=$commands[0];
1.447     foxr     10816: 
1.596.2.12.2.  1(raebur 10817:0):     &init_perm();
                   10818:0):     if (!$env{'request.course.id'}) {
                   10819:0):         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10820:0):                 ($command =~ /^scantronupload/)) {
                   10821:0):             # Not in a course.
                   10822:0):             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10823:0):             return HTTP_NOT_ACCEPTABLE;
                   10824:0):         }
                   10825:0):     } elsif (!%perm) {
                   10826:0):         $request->internal_redirect('/adm/quickgrades');
                   10827:0):         return OK;
                   10828:0):     }
                   10829:0):     &Apache::loncommon::content_type($request,'text/html');
                   10830:0):     $request->send_http_header;
                   10831:0): 
1.160     albertel 10832:     if ($#commands > 0) {
                   10833: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10834:     }
1.447     foxr     10835: 
1.596.2.12.2.  1(raebur 10836:0): # see what the symb is
                   10837:0): 
                   10838:0):     my $symb=$env{'form.symb'};
                   10839:0):     unless ($symb) {
                   10840:0):        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10841:0):        $symb=&Apache::lonnet::symbread($url);
                   10842:0):     }
                   10843:0):     &Apache::lonenc::check_decrypt(\$symb);
                   10844:0): 
1.513     foxr     10845:     $ssi_error = 0;
1.596.2.12.2.  1(raebur 10846:0):     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
                   10847:0): #
                   10848:0): # Not called from a resource, but inside a course
                   10849:0): #
                   10850:0):         &startpage($request,undef,[],1,1);
                   10851:0):         &select_problem($request);
1.41      ng       10852:     } else {
1.596.2.12.2.  1(raebur 10853:0):         if ($command eq 'submission' && $perm{'vgr'}) {
                   10854:0):             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
          (raeburn 10855:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10856:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10857:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10858:):                                               $env{'form.userdom'});
                   10859:):             }
          1(raebur 10860:0):             my $divforres;
                   10861:0):             if ($env{'form.student'} eq '') {
                   10862:0):                 $js .= &part_selector_js();
                   10863:0):                 $onload = "toggleParts('gradesub');";
                   10864:0):             } else {
                   10865:0):                 $divforres = 1;
                   10866:0):             }
                   10867:0):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
          (raeburn 10868:):             if ($versionform) {
                   10869:):                 $request->print($versionform);
                   10870:):             }
          1(raebur 10871:0):             ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
          (raeburn 10872:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10873:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10874:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10875:):                                           $env{'form.userdom'},
                   10876:):                                           $env{'form.inhibitmenu'});
                   10877:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10878:):             if ($versionform) {
                   10879:):                 $request->print($versionform);
                   10880:):             }
                   10881:):             $request->print('<br clear="all" />');
                   10882:):             $request->print(&show_previous_task_version($request,$symb));
          1(raebur 10883:0):         } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
                   10884:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10885:0):                                        {href=>'',text=>'Select student'}],1,1);
                   10886:0):             &pickStudentPage($request,$symb);
                   10887:0):         } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
                   10888:0):             &startpage($request,$symb,
                   10889:0):                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10890:0):                                        {href=>'',text=>'Select student'},
                   10891:0):                                        {href=>'',text=>'Grade student'}],1,1);
                   10892:0):             &displayPage($request,$symb);
                   10893:0):         } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
                   10894:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10895:0):                                        {href=>'',text=>'Select student'},
                   10896:0):                                        {href=>'',text=>'Grade student'},
                   10897:0):                                        {href=>'',text=>'Store grades'}],1,1);
                   10898:0):             &updateGradeByPage($request,$symb);
                   10899:0):         } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
                   10900:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10901:0):                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
                   10902:0):             &processGroup($request,$symb);
                   10903:0):         } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
                   10904:0):             &startpage($request,$symb);
                   10905:0):             $request->print(&grading_menu($request,$symb));
                   10906:0):         } elsif ($command eq 'individual' && $perm{'vgr'}) {
                   10907:0):             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
                   10908:0):             $request->print(&submit_options($request,$symb));
                   10909:0):         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
                   10910:0):             my $js = &part_selector_js();
                   10911:0):             my $onload = "toggleParts('gradesub');";
                   10912:0):             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
                   10913:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   10914:0):             $request->print(&listStudents($request,$symb,'graded'));
                   10915:0):         } elsif ($command eq 'table' && $perm{'vgr'}) {
                   10916:0):             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
                   10917:0):             $request->print(&submit_options_table($request,$symb));
                   10918:0):         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
                   10919:0):             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
                   10920:0):             $request->print(&submit_options_sequence($request,$symb));
                   10921:0):         } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
                   10922:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
                   10923:0):             $request->print(&viewgrades($request,$symb));
                   10924:0):         } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
                   10925:0):             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10926:0):                                        {href=>'',text=>'Store grades'}]);
                   10927:0):             $request->print(&processHandGrade($request,$symb));
                   10928:0):         } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
                   10929:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10930:0):                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10931:0):                                                                              text=>"Modify grades"},
                   10932:0):                                        {href=>'', text=>"Store grades"}]);
                   10933:0):             $request->print(&editgrades($request,$symb));
                   10934:0):         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
                   10935:0):             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
                   10936:0):             $request->print(&initialverifyreceipt($request,$symb));
                   10937:0):         } elsif ($command eq 'verify' && $perm{'vgr'}) {
                   10938:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10939:0):                                        {href=>'',text=>'Verification Result'}]);
                   10940:0):             $request->print(&verifyreceipt($request,$symb));
1.400     www      10941:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10942:0):             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
                   10943:0):             $request->print(&process_clicker($request,$symb));
1.400     www      10944:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10945:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10946:0):                                        {href=>'', text=>'Process clicker file'}]);
                   10947:0):             $request->print(&process_clicker_file($request,$symb));
1.414     www      10948:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.596.2.12.2.  1(raebur 10949:0):             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10950:0):                                        {href=>'', text=>'Process clicker file'},
                   10951:0):                                        {href=>'', text=>'Store grades'}]);
                   10952:0):             $request->print(&assign_clicker_grades($request,$symb));
                   10953:0):         } elsif ($command eq 'csvform' && $perm{'mgr'}) {
                   10954:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10955:0):             $request->print(&upcsvScores_form($request,$symb));
                   10956:0):         } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
                   10957:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10958:0):             $request->print(&csvupload($request,$symb));
                   10959:0):         } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
                   10960:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10961:0):             $request->print(&csvuploadmap($request,$symb));
                   10962:0):         } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
                   10963:0):             if ($env{'form.associate'} ne 'Reverse Association') {
                   10964:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10965:0):                 $request->print(&csvuploadoptions($request,$symb));
                   10966:0):             } else {
                   10967:0):                 if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10968:0):                     $env{'form.upfile_associate'} = 'reverse';
                   10969:0):                 } else {
                   10970:0):                     $env{'form.upfile_associate'} = 'forward';
                   10971:0):                 }
                   10972:0):                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10973:0):                 $request->print(&csvuploadmap($request,$symb));
                   10974:0):             }
                   10975:0):         } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10976:0):             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
                   10977:0):             $request->print(&csvuploadassign($request,$symb));
                   10978:0):         } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
                   10979:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10980:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   10981:0):             $request->print(&scantron_selectphase($request,undef,$symb));
                   10982:0):         } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10983:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   10984:0):             $request->print(&scantron_do_warning($request,$symb));
                   10985:0):         } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10986:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   10987:0):             $request->print(&scantron_validate_file($request,$symb));
                   10988:0):         } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
                   10989:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   10990:0):             $request->print(&scantron_process_students($request,$symb));
                   10991:0):         } elsif ($command eq 'scantronupload' &&
                   10992:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10993:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   10994:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10995:0):                        undef,undef,undef,undef,'toggleScantab(document.rules);');
                   10996:0):             $request->print(&scantron_upload_scantron_data($request,$symb));
                   10997:0):         } elsif ($command eq 'scantronupload_save' &&
                   10998:0):                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10999:0):                   &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
                   11000:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11001:0):             $request->print(&scantron_upload_scantron_data_save($request,$symb));
                   11002:0):         } elsif ($command eq 'scantron_download' &&
                   11003:0):                  &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   11004:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11005:0):             $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  11006:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.596.2.12.2.  1(raebur 11007:0):             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11008:0):             $request->print(&checkscantron_results($request,$symb));
                   11009:0):         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11010:0):             my $js = &part_selector_js();
                   11011:0):             my $onload = "toggleParts('gradingMenu');";
                   11012:0):             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
                   11013:0):                        undef,undef,undef,undef,undef,$js,$onload);
                   11014:0):             $request->print(&submit_options_download($request,$symb));
                   11015:0):          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11016:0):             &startpage($request,$symb,
                   11017:0):    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   11018:0):     {href=>'', text=>'Download submitted files'}],
                   11019:0):                undef,undef,undef,undef,undef,undef,undef,1);
                   11020:0):             &submit_download_link($request,$symb);
                   11021:0):         } elsif ($command) {
                   11022:0):             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
                   11023:0):             $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
                   11024:0):         }
1.2       albertel 11025:     }
1.513     foxr     11026:     if ($ssi_error) {
                   11027: 	&ssi_print_error($request);
                   11028:     }
1.353     albertel 11029:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 11030:     &reset_caches();
1.596.2.4  raeburn  11031:     return OK;
1.44      ng       11032: }
                   11033: 
1.1       albertel 11034: 1;
                   11035: 
1.13      albertel 11036: __END__;
1.531     jms      11037: 
                   11038: 
                   11039: =head1 NAME
                   11040: 
                   11041: Apache::grades
                   11042: 
                   11043: =head1 SYNOPSIS
                   11044: 
                   11045: Handles the viewing of grades.
                   11046: 
                   11047: This is part of the LearningOnline Network with CAPA project
                   11048: described at http://www.lon-capa.org.
                   11049: 
                   11050: =head1 OVERVIEW
                   11051: 
                   11052: Do an ssi with retries:
                   11053: While I'd love to factor out this with the vesrion in lonprintout,
                   11054: 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
                   11055: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11056: 
                   11057: At least the logic that drives this has been pulled out into loncommon.
                   11058: 
                   11059: 
                   11060: 
                   11061: ssi_with_retries - Does the server side include of a resource.
                   11062:                      if the ssi call returns an error we'll retry it up to
                   11063:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 11064:4):                      If we still have a problem, no text is appended to the
1.531     jms      11065:                      output and we set some global variables.
                   11066:                      to indicate to the caller an SSI error occurred.  
                   11067:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 11068:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      11069:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11070:                      by informing the user that this happened.
                   11071: 
                   11072: Parameters:
                   11073:   resource   - The resource to include.  This is passed directly, without
                   11074:                interpretation to lonnet::ssi.
                   11075:   form       - The form hash parameters that guide the interpretation of the resource
                   11076:                
                   11077:   retries    - Number of retries allowed before giving up completely.
                   11078: Returns:
                   11079:   On success, returns the rendered resource identified by the resource parameter.
                   11080: Side Effects:
                   11081:   The following global variables can be set:
                   11082:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11083:                               It is up to the caller to initialize this to false
                   11084:                               if desired.
                   11085:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11086:                               of the resource that could not be rendered by the ssi
                   11087:                               call.
                   11088:    ssi_error_message   - The error string fetched from the ssi response
                   11089:                               in the event of an error.
                   11090: 
                   11091: 
                   11092: =head1 HANDLER SUBROUTINE
                   11093: 
                   11094: ssi_with_retries()
                   11095: 
                   11096: =head1 SUBROUTINES
                   11097: 
                   11098: =over
                   11099: 
                   11100: =item scantron_get_correction() : 
                   11101: 
                   11102:    Builds the interface screen to interact with the operator to fix a
                   11103:    specific error condition in a specific scanline
                   11104: 
                   11105:  Arguments:
                   11106:     $r           - Apache request object
                   11107:     $i           - number of the current scanline
                   11108:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.596.2.12.2.  9(raebur 11109:9):     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11110:     $line        - full contents of the current scanline
                   11111:     $error       - error condition, valid values are
                   11112:                    'incorrectCODE', 'duplicateCODE',
                   11113:                    'doublebubble', 'missingbubble',
                   11114:                    'duplicateID', 'incorrectID'
                   11115:     $arg         - extra information needed
                   11116:        For errors:
                   11117:          - duplicateID   - paper number that this studentID was seen before on
                   11118:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11119:                            seen on before
                   11120:          - incorrectCODE - current incorrect CODE 
                   11121:          - doublebubble  - array ref of the bubble lines that have double
                   11122:                            bubble errors
                   11123:          - missingbubble - array ref of the bubble lines that have missing
                   11124:                            bubble errors
                   11125: 
1.596.2.12.2.  6(raebur 11126:3):    $randomorder - True if exam folder has randomorder set
                   11127:3):    $randompick  - True if exam folder has randompick set
                   11128:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11129:3):                      for current line to question number used for same question
                   11130:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   11131:3):    $startline   - Reference to hash where key is question number (0 is first)
                   11132:3):                   and value is number of first bubble line for current student
                   11133:3):                   or code-based randompick and/or randomorder.
                   11134:3): 
                   11135:3): 
1.531     jms      11136: =item  scantron_get_maxbubble() : 
                   11137: 
1.582     raeburn  11138:    Arguments:
                   11139:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11140:                       failure to retrieve a navmap object.
                   11141:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11142:        calling routine should trap the error condition and display the warning
                   11143:        found in &navmap_errormsg().
                   11144: 
1.596.2.12.2.  (raeburn 11145:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   11146:): 
1.531     jms      11147:    Returns the maximum number of bubble lines that are expected to
                   11148:    occur. Does this by walking the selected sequence rendering the
                   11149:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11150:    for what the current value of the problem counter is.
                   11151: 
                   11152:    Caches the results to $env{'form.scantron_maxbubble'},
                   11153:    $env{'form.scantron.bubble_lines.n'}, 
                   11154:    $env{'form.scantron.first_bubble_line.n'} and
                   11155:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 11156:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      11157:    lines for response n and number of the first bubble line for response n,
                   11158:    and a comma separated list of numbers of bubble lines for sub-questions
                   11159:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11160: 
                   11161: 
                   11162: =item  scantron_validate_missingbubbles() : 
                   11163: 
                   11164:    Validates all scanlines in the selected file to not have any
                   11165:     answers that don't have bubbles that have not been verified
                   11166:     to be bubble free.
                   11167: 
                   11168: =item  scantron_process_students() : 
                   11169: 
1.596.2.6  raeburn  11170:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11171: 
                   11172:    The parsed scanline hash is added to %env 
                   11173: 
                   11174:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11175:    foreach resource , with the form data of
                   11176: 
                   11177: 	'submitted'     =>'scantron' 
                   11178: 	'grade_target'  =>'grade',
                   11179: 	'grade_username'=> username of student
                   11180: 	'grade_domain'  => domain of student
                   11181: 	'grade_courseid'=> of course
                   11182: 	'grade_symb'    => symb of resource to grade
                   11183: 
                   11184:     This triggers a grading pass. The problem grading code takes care
                   11185:     of converting the bubbled letter information (now in %env) into a
                   11186:     valid submission.
                   11187: 
                   11188: =item  scantron_upload_scantron_data() :
                   11189: 
1.596.2.6  raeburn  11190:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11191: 
                   11192: =item  scantron_upload_scantron_data_save() : 
                   11193: 
                   11194:    Adds a provided bubble information data file to the course if user
                   11195:    has the correct privileges to do so. 
                   11196: 
                   11197: =item  valid_file() :
                   11198: 
                   11199:    Validates that the requested bubble data file exists in the course.
                   11200: 
                   11201: =item  scantron_download_scantron_data() : 
                   11202: 
                   11203:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  11204:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11205:    course.
                   11206: 
                   11207: =item  scantron_validate_ID() : 
                   11208: 
                   11209:    Validates all scanlines in the selected file to not have any
1.556     weissno  11210:    invalid or underspecified student/employee IDs
1.531     jms      11211: 
1.582     raeburn  11212: =item navmap_errormsg() :
                   11213: 
                   11214:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11215:    Should be called whenever the request to instantiate a navmap object fails.  
                   11216: 
1.531     jms      11217: =back
                   11218: 
                   11219: =cut

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