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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.773   ! raeburn     4: # $Id: grades.pm,v 1.772 2020/08/29 16:39:00 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.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.752     raeburn    49: use Apache::lontexconvert();
1.170     albertel   50: use String::Similarity;
1.760     raeburn    51: use HTML::Parser();
                     52: use File::MMagic;
1.359     www        53: use LONCAPA;
                     54: 
1.315     bowersj2   55: use POSIX qw(floor);
1.87      www        56: 
1.435     foxr       57: 
1.513     foxr       58: 
1.435     foxr       59: my %perm=();
1.674     raeburn    60: my %old_essays=();
1.447     foxr       61: 
1.513     foxr       62: #  These variables are used to recover from ssi errors
                     63: 
                     64: my $ssi_retries = 5;
                     65: my $ssi_error;
                     66: my $ssi_error_resource;
                     67: my $ssi_error_message;
                     68: 
                     69: 
                     70: sub ssi_with_retries {
                     71:     my ($resource, $retries, %form) = @_;
                     72:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     73:     if ($response->is_error) {
                     74: 	$ssi_error          = 1;
                     75: 	$ssi_error_resource = $resource;
                     76: 	$ssi_error_message  = $response->code . " " . $response->message;
                     77:     }
                     78: 
                     79:     return $content;
                     80: 
                     81: }
                     82: #
                     83: #  Prodcuces an ssi retry failure error message to the user:
                     84: #
                     85: 
                     86: sub ssi_print_error {
                     87:     my ($r) = @_;
1.516     raeburn    88:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     89:     $r->print('
                     90: <br />
                     91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     92: <p>
                     93: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     95: '.&mt('Error:').' '.$ssi_error_message.'
                     96: </p>
                     97: <p>'.
                     98: &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 />'.
                     99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    100: '</p>');
                    101:     return;
1.513     foxr      102: }
                    103: 
1.44      ng        104: #
1.146     albertel  105: # --- Retrieve the parts from the metadata file.---
1.598     www       106: # Returns an array of everything that the resources stores away
                    107: #
                    108: 
1.44      ng        109: sub getpartlist {
1.582     raeburn   110:     my ($symb,$errorref) = @_;
1.439     albertel  111: 
                    112:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   113:     unless (ref($navmap)) {
                    114:         if (ref($errorref)) { 
                    115:             $$errorref = 'navmap';
                    116:             return;
                    117:         }
                    118:     }
1.439     albertel  119:     my $res      = $navmap->getBySymb($symb);
                    120:     my $partlist = $res->parts();
                    121:     my $url      = $res->src();
1.745     raeburn   122:     my $toolsymb;
                    123:     if ($url =~ /ext\.tool$/) {
                    124:         $toolsymb = $symb;
                    125:     }
                    126:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
1.439     albertel  127: 
1.146     albertel  128:     my @stores;
1.439     albertel  129:     foreach my $part (@{ $partlist }) {
1.146     albertel  130: 	foreach my $key (@metakeys) {
                    131: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    132: 	}
                    133:     }
                    134:     return @stores;
1.2       albertel  135: }
                    136: 
1.129     ng        137: #--- Format fullname, username:domain if different for display
                    138: #--- Use anywhere where the student names are listed
                    139: sub nameUserString {
                    140:     my ($type,$fullname,$uname,$udom) = @_;
                    141:     if ($type eq 'header') {
1.485     albertel  142: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        143:     } else {
1.398     albertel  144: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    145: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        146:     }
                    147: }
                    148: 
1.44      ng        149: #--- Get the partlist and the response type for a given problem. ---
1.773   ! raeburn   150: #--- Count responseIDs, essayresponse items, and dropbox items ---
1.623     www       151: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.773   ! raeburn   168:     my ($numresp,$numessay,$numdropbox) = (0,0,0);
1.392     albertel  169:     my %vPart = 
                    170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  171:     my (%response_types,%handgrade);
                    172:     foreach my $part (@{ $partlist }) {
1.392     albertel  173: 	next if (%vPart && !exists($vPart{$part}));
                    174: 
1.377     albertel  175: 	my @types = $res->responseType($part);
                    176: 	my @ids = $res->responseIds($part);
                    177: 	for (my $i=0; $i < scalar(@ids); $i++) {
1.773   ! raeburn   178:             $numresp ++;
1.377     albertel  179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
1.773   ! raeburn   180:             if ($types[$i] eq 'essay') {
        !           181:                 $numessay ++;
        !           182:                 if (&Apache::lonnet::EXT("resource.$part".'_'.$ids[$i].".uploadedfiletypes",$symb)) {
        !           183:                     $numdropbox ++;
        !           184:                 }
        !           185:             }
1.377     albertel  186: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    187: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    188: 				     '.handgrade',$symb);
1.41      ng        189: 	}
                    190:     }
1.773   ! raeburn   191:     return ($partlist,\%handgrade,\%response_types,$numresp,$numessay,$numdropbox);
1.39      ng        192: }
                    193: 
1.375     albertel  194: sub flatten_responseType {
                    195:     my ($responseType) = @_;
                    196:     my @part_response_id =
                    197: 	map { 
                    198: 	    my $part = $_;
                    199: 	    map {
                    200: 		[$part,$_]
                    201: 		} sort(keys(%{ $responseType->{$part} }));
                    202: 	} sort(keys(%$responseType));
                    203:     return @part_response_id;
                    204: }
                    205: 
1.207     albertel  206: sub get_display_part {
1.324     albertel  207:     my ($partID,$symb)=@_;
1.207     albertel  208:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    209:     if (defined($display) and $display ne '') {
1.577     bisitz    210:         $display.= ' (<span class="LC_internal_info">'
                    211:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  212:     } else {
                    213: 	$display=$partID;
                    214:     }
                    215:     return $display;
                    216: }
1.269     raeburn   217: 
1.773   ! raeburn   218: #--- Show parts and response type
        !           219: sub showResourceInfo {
        !           220:     my ($symb,$partlist,$responseType,$formname,$checkboxes,$uploads) = @_;
        !           221:     unless ((ref($partlist) eq 'ARRAY') && (ref($responseType) eq 'HASH')) {
        !           222:         return '<br clear="all">';
        !           223:     }
        !           224:     my $coltitle = &mt('Problem Part Shown');
        !           225:     if ($checkboxes) {
        !           226:         $coltitle = &mt('Problem Part');
        !           227:     } else {
        !           228:         my $checkedparts = 0;
        !           229:         foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
        !           230:             if (grep(/^\Q$partid\E$/,@{$partlist})) {
        !           231:                 $checkedparts ++;
        !           232:             }
        !           233:         }
        !           234:         if ($checkedparts == scalar(@{$partlist})) {
        !           235:             return '<br clear="all">';
        !           236:         }
        !           237:         if ($uploads) {
        !           238:             $coltitle = &mt('Problem Part Selected');
        !           239:         }
        !           240:     }
        !           241:     my $result = '<div class="LC_left_float" style="display:inline-block;">';
        !           242:     if ($checkboxes) {
        !           243:         my $legend = &mt('Parts to display');
        !           244:         if ($uploads) {
        !           245:             $legend = &mt('Part(s) with dropbox');
        !           246:         }
        !           247:         $result .= '<fieldset style="display:inline-block;"><legend>'.$legend.'</legend>'.
        !           248:                    '<span class="LC_nobreak">'.
        !           249:                    '<label><input type="radio" name="chooseparts" value="0" onclick="toggleParts('."'$formname'".');" checked="checked" />'.
        !           250:                    &mt('All parts').'</label>'.('&nbsp;'x2).
        !           251:                    '<label><input type="radio" name="chooseparts" value="1" onclick="toggleParts('."'$formname'".');" />'.
        !           252:                    &mt('Selected parts').'</label></span>'.
        !           253:                    '<div id="LC_partselector" style="display:none">';
        !           254:     }
        !           255:     $result .= &Apache::loncommon::start_data_table()
        !           256:               .&Apache::loncommon::start_data_table_header_row();
        !           257:     if ($checkboxes) {
        !           258:         $result .= '<th>'.&mt('Display?').'</th>';
        !           259:     }
        !           260:     $result .= '<th>'.$coltitle.'</th>'
        !           261:               .'<th>'.&mt('Res. ID').'</th>'
        !           262:               .'<th>'.&mt('Type').'</th>'
        !           263:               .&Apache::loncommon::end_data_table_header_row();
        !           264:     my %partsseen;
        !           265:     foreach my $partID (sort(keys(%$responseType))) {
        !           266:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
        !           267:             my $responsetype = $responseType->{$partID}->{$resID};
        !           268:             if ($uploads) {
        !           269:                 next unless ($responsetype eq 'essay');
        !           270:                 next unless (&Apache::lonnet::EXT("resource.$partID".'_'."$resID.uploadedfiletypes",$symb));
        !           271:             }
        !           272:             my $display_part=&get_display_part($partID,$symb);
        !           273:             if (exists($partsseen{$partID})) {
        !           274:                 $result.=&Apache::loncommon::continue_data_table_row();
        !           275:             } else {
        !           276:                 $partsseen{$partID}=scalar(keys(%{$responseType->{$partID}}));
        !           277:                 $result.=&Apache::loncommon::start_data_table_row().
        !           278:                          '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">';
        !           279:                 if ($checkboxes) {
        !           280:                     $result.='<input type="checkbox" name="vPart" checked="checked" value="'.$partID.'" /></td>'.
        !           281:                              '<td rowspan="'.$partsseen{$partID}.'" style="vertical-align:middle">'.$display_part.'</td>';
        !           282:                 } else {
        !           283:                     $result.=$display_part.'</td>';
        !           284:                 }
        !           285:             }
        !           286:             $result.='<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
        !           287:                     .'<td>'.&mt($responsetype).'</td>'
        !           288:                     .&Apache::loncommon::end_data_table_row();
        !           289:         }
        !           290:     }
        !           291:     $result.=&Apache::loncommon::end_data_table();
        !           292:     if ($checkboxes) {
        !           293:         $result .= '</div></fieldset>';
        !           294:     }
        !           295:     $result .= '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
        !           296:     return $result;
        !           297: }
        !           298: 
        !           299: sub part_selector_js {
        !           300:     my $js = <<"END";
        !           301: function toggleParts(formname) {
        !           302:     if (document.getElementById('LC_partselector')) {
        !           303:         var index = '';
        !           304:         if (document.forms.length) {
        !           305:             for (var i=0; i<document.forms.length; i++) {
        !           306:                 if (document.forms[i].name == formname) {
        !           307:                     index = i;
        !           308:                     break;
        !           309:                 }
        !           310:             }
        !           311:         }
        !           312:         if ((index != '') && (document.forms[index].elements['chooseparts'].length > 1)) {
        !           313:             for (var i=0; i<document.forms[index].elements['chooseparts'].length; i++) {
        !           314:                 if (document.forms[index].elements['chooseparts'][i].checked) {
        !           315:                    var val = document.forms[index].elements['chooseparts'][i].value;
        !           316:                     if (document.forms[index].elements['chooseparts'][i].value == 1) {
        !           317:                         document.getElementById('LC_partselector').style.display = 'block';
        !           318:                     } else {
        !           319:                         document.getElementById('LC_partselector').style.display = 'none';
        !           320:                     }
        !           321:                 }
        !           322:             }
        !           323:         }
        !           324:     }
        !           325: }
        !           326: END
        !           327:     return &Apache::lonhtmlcommon::scripttag($js);
        !           328: }
        !           329: 
1.434     albertel  330: sub reset_caches {
                    331:     &reset_analyze_cache();
                    332:     &reset_perm();
1.674     raeburn   333:     &reset_old_essays();
1.434     albertel  334: }
                    335: 
                    336: {
                    337:     my %analyze_cache;
1.557     raeburn   338:     my %analyze_cache_formkeys;
1.148     albertel  339: 
1.434     albertel  340:     sub reset_analyze_cache {
                    341: 	undef(%analyze_cache);
1.557     raeburn   342:         undef(%analyze_cache_formkeys);
1.434     albertel  343:     }
                    344: 
                    345:     sub get_analyze {
1.649     raeburn   346: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  347: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   348:         if ($type eq 'randomizetry') {
                    349:             if ($trial ne '') {
                    350:                 $key .= "\0".$trial;
                    351:             }
                    352:         }
1.557     raeburn   353: 	if (exists($analyze_cache{$key})) {
                    354:             my $getupdate = 0;
                    355:             if (ref($add_to_hash) eq 'HASH') {
                    356:                 foreach my $item (keys(%{$add_to_hash})) {
                    357:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    358:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    359:                             $getupdate = 1;
                    360:                             last;
                    361:                         }
                    362:                     } else {
                    363:                         $getupdate = 1;
                    364:                     }
                    365:                 }
                    366:             }
                    367:             if (!$getupdate) {
                    368:                 return $analyze_cache{$key};
                    369:             }
                    370:         }
1.434     albertel  371: 
                    372: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    373: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   374:         my %form = ('grade_target'      => 'analyze',
                    375:                     'grade_domain'      => $udom,
                    376:                     'grade_symb'        => $symb,
                    377:                     'grade_courseid'    =>  $env{'request.course.id'},
                    378:                     'grade_username'    => $uname,
                    379:                     'grade_noincrement' => $no_increment);
1.649     raeburn   380:         if ($bubbles_per_row ne '') {
                    381:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    382:         }
1.640     raeburn   383:         if ($type eq 'randomizetry') {
                    384:             $form{'grade_questiontype'} = $type;
                    385:             if ($rndseed ne '') {
                    386:                 $form{'grade_rndseed'} = $rndseed;
                    387:             }
                    388:         }
1.557     raeburn   389:         if (ref($add_to_hash)) {
                    390:             %form = (%form,%{$add_to_hash});
1.640     raeburn   391:         }
1.557     raeburn   392: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  393: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    394: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   395:         if (ref($add_to_hash) eq 'HASH') {
                    396:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    397:         } else {
                    398:             $analyze_cache_formkeys{$key} = {};
                    399:         }
1.434     albertel  400: 	return $analyze_cache{$key} = \%analyze;
                    401:     }
                    402: 
                    403:     sub get_order {
1.640     raeburn   404: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    405: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  406: 	return $analyze->{"$partid.$respid.shown"};
                    407:     }
                    408: 
                    409:     sub get_radiobutton_correct_foil {
1.640     raeburn   410: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    411: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    412:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   413:         if (ref($foils) eq 'ARRAY') {
                    414: 	    foreach my $foil (@{$foils}) {
                    415: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    416: 		    return $foil;
                    417: 	        }
1.434     albertel  418: 	    }
                    419: 	}
                    420:     }
1.554     raeburn   421: 
                    422:     sub scantron_partids_tograde {
1.741     raeburn   423:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
1.554     raeburn   424:         my (%analysis,@parts);
                    425:         if (ref($resource)) {
                    426:             my $symb = $resource->symb();
1.557     raeburn   427:             my $add_to_form;
                    428:             if ($check_for_randomlist) {
                    429:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    430:             }
1.741     raeburn   431:             if ($scancode) {
                    432:                 if (ref($add_to_form) eq 'HASH') {
                    433:                     $add_to_form->{'code_for_randomlist'} = $scancode;
                    434:                 } else {
                    435:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
                    436:                 }
                    437:             }
1.767     raeburn   438:             my $analyze =
1.649     raeburn   439:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    440:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   441:             if (ref($analyze) eq 'HASH') {
                    442:                 %analysis = %{$analyze};
                    443:             }
                    444:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    445:                 foreach my $part (@{$analysis{'parts'}}) {
                    446:                     my ($id,$respid) = split(/\./,$part);
                    447:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    448:                         push(@parts,$part);
                    449:                     }
                    450:                 }
                    451:             }
                    452:         }
                    453:         return (\%analysis,\@parts);
                    454:     }
                    455: 
1.148     albertel  456: }
1.434     albertel  457: 
1.118     ng        458: #--- Clean response type for display
1.335     albertel  459: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    460: #        response types only.
1.118     ng        461: sub cleanRecord {
1.336     albertel  462:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   463: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  464:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  465:     if ($response =~ /^(option|rank)$/) {
                    466: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     467:         my @answer = %answer;
1.767     raeburn   468:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  469: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    470: 	my ($toprow,$bottomrow);
                    471: 	foreach my $foil (@$order) {
                    472: 	    if ($grading{$foil} == 1) {
                    473: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    474: 	    } else {
                    475: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    476: 	    }
1.398     albertel  477: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  478: 	}
                    479: 	return '<blockquote><table border="1">'.
1.466     albertel  480: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    481: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   482: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  483:     } elsif ($response eq 'match') {
                    484: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     485:         my @answer = %answer;
1.767     raeburn   486:         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  487: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    488: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    489: 	my ($toprow,$middlerow,$bottomrow);
                    490: 	foreach my $foil (@$order) {
                    491: 	    my $item=shift(@items);
                    492: 	    if ($grading{$foil} == 1) {
                    493: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  494: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  495: 	    } else {
                    496: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  497: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  498: 	    }
1.398     albertel  499: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        500: 	}
1.126     ng        501: 	return '<blockquote><table border="1">'.
1.466     albertel  502: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    503: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  504: 	    $middlerow.'</tr>'.
1.466     albertel  505: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   506: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  507:     } elsif ($response eq 'radiobutton') {
                    508: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     509:         my @answer = %answer;
                    510:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  511: 	my ($toprow,$bottomrow);
1.434     albertel  512: 	my $correct = 
1.640     raeburn   513: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  514: 	foreach my $foil (@$order) {
1.148     albertel  515: 	    if (exists($answer{$foil})) {
1.434     albertel  516: 		if ($foil eq $correct) {
1.466     albertel  517: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  518: 		} else {
1.466     albertel  519: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  520: 		}
                    521: 	    } else {
1.466     albertel  522: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  523: 	    }
1.398     albertel  524: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  525: 	}
                    526: 	return '<blockquote><table border="1">'.
1.466     albertel  527: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    528: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   529: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  530:     } elsif ($response eq 'essay') {
1.257     albertel  531: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        532: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  533: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    534: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        535: 
1.257     albertel  536: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    537: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    538: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    539: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    540: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    541: 	    $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        542: 	}
1.751     raeburn   543:         $answer = &Apache::lontexconvert::msgtexconverted($answer);
1.730     kruse     544: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  545:     } elsif ( $response eq 'organic') {
1.721     bisitz    546:         my $result=&mt('Smile representation: [_1]',
                    547:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  548: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    549: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    550: 	return $result;
1.335     albertel  551:     } elsif ( $response eq 'Task') {
                    552: 	if ( $answer eq 'SUBMITTED') {
                    553: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  554: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  555: 	    return $result;
                    556: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    557: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    558: 			       keys(%{$record}));
                    559: 	    return join('<br />',($version,@matches));
                    560: 			       
                    561: 			       
                    562: 	} else {
                    563: 	    my $result =
                    564: 		'<p>'
                    565: 		.&mt('Overall result: [_1]',
                    566: 		     $record->{$version."resource.$respid.$partid.status"})
                    567: 		.'</p>';
                    568: 	    
                    569: 	    $result .= '<ul>';
                    570: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    571: 			     keys(%{$record}));
                    572: 	    foreach my $grade (sort(@grade)) {
                    573: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    574: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    575: 				     $dim, $record->{$grade}).
                    576: 			  '</li>';
                    577: 	    }
                    578: 	    $result.='</ul>';
                    579: 	    return $result;
                    580: 	}
1.716     bisitz    581:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    582:         # Respect multiple input fields, see Bug #5409
1.440     albertel  583: 	$answer = 
                    584: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    585: 							      $answer);
1.720     kruse     586: 	return $answer;
1.122     ng        587:     }
1.720     kruse     588:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        589: }
                    590: 
                    591: #-- A couple of common js functions
                    592: sub commonJSfunctions {
                    593:     my $request = shift;
1.597     wenzelju  594:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        595:     function radioSelection(radioButton) {
                    596: 	var selection=null;
                    597: 	if (radioButton.length > 1) {
                    598: 	    for (var i=0; i<radioButton.length; i++) {
                    599: 		if (radioButton[i].checked) {
                    600: 		    return radioButton[i].value;
                    601: 		}
                    602: 	    }
                    603: 	} else {
                    604: 	    if (radioButton.checked) return radioButton.value;
                    605: 	}
                    606: 	return selection;
                    607:     }
                    608: 
                    609:     function pullDownSelection(selectOne) {
                    610: 	var selection="";
                    611: 	if (selectOne.length > 1) {
                    612: 	    for (var i=0; i<selectOne.length; i++) {
                    613: 		if (selectOne[i].selected) {
                    614: 		    return selectOne[i].value;
                    615: 		}
                    616: 	    }
                    617: 	} else {
1.138     albertel  618:             // only one value it must be the selected one
                    619: 	    return selectOne.value;
1.118     ng        620: 	}
                    621:     }
                    622: COMMONJSFUNCTIONS
                    623: }
                    624: 
1.44      ng        625: #--- Dumps the class list with usernames,list of sections,
                    626: #--- section, ids and fullnames for each user.
                    627: sub getclasslist {
1.750     raeburn   628:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  629:     my @getsec;
1.450     banghart  630:     my @getgroup;
1.442     banghart  631:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  632:     if (!ref($getsec)) {
                    633: 	if ($getsec ne '' && $getsec ne 'all') {
                    634: 	    @getsec=($getsec);
                    635: 	}
                    636:     } else {
                    637: 	@getsec=@{$getsec};
                    638:     }
                    639:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  640:     if (!ref($getgroup)) {
                    641: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    642: 	    @getgroup=($getgroup);
                    643: 	}
                    644:     } else {
                    645: 	@getgroup=@{$getgroup};
                    646:     }
                    647:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  648: 
1.449     banghart  649:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  650:     # Bail out if we were unable to get the classlist
1.56      matthew   651:     return if (! defined($classlist));
1.449     banghart  652:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   653:     #
                    654:     my %sections;
                    655:     my %fullnames;
1.750     raeburn   656:     my ($cdom,$cnum,$partlist);
                    657:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    658:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    659:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    660:         my $res_error;
1.773   ! raeburn   661:         ($partlist) = &response_type($symb,\$res_error);
1.750     raeburn   662:     }
1.205     matthew   663:     foreach my $student (keys(%$classlist)) {
                    664:         my $end      = 
                    665:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    666:         my $start    = 
                    667:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    668:         my $id       = 
                    669:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    670:         my $section  = 
                    671:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    672:         my $fullname = 
                    673:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    674:         my $status   = 
                    675:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  676:         my $group   = 
                    677:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        678: 	# filter students according to status selected
1.750     raeburn   679: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  680: 	    if (!($stu_status =~ $status)) {
1.450     banghart  681: 		delete($classlist->{$student});
1.76      ng        682: 		next;
                    683: 	    }
                    684: 	}
1.450     banghart  685: 	# filter students according to groups selected
1.453     banghart  686: 	my @stu_groups = split(/,/,$group);
1.450     banghart  687: 	if (@getgroup) {
                    688: 	    my $exclude = 1;
1.454     banghart  689: 	    foreach my $grp (@getgroup) {
                    690: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  691: 	            if ($stu_group eq $grp) {
                    692: 	                $exclude = 0;
                    693:     	            } 
1.450     banghart  694: 	        }
1.453     banghart  695:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   696:         	    $exclude = 0;
1.453     banghart  697:         	}
1.450     banghart  698: 	    }
                    699: 	    if ($exclude) {
                    700: 	        delete($classlist->{$student});
1.750     raeburn   701: 		next;
1.450     banghart  702: 	    }
                    703: 	}
1.750     raeburn   704:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    705:             my $udom =
                    706:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    707:             my $uname =
                    708:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    709:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    710:                 if ($submitonly eq 'queued') {
                    711:                     my %queue_status =
                    712:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    713:                                                                 $udom,$uname);
                    714:                     if (!defined($queue_status{'gradingqueue'})) {
                    715:                         delete($classlist->{$student});
                    716:                         next;
                    717:                     }
                    718:                 } else {
                    719:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    720:                     my $submitted = 0;
                    721:                     my $graded = 0;
                    722:                     my $incorrect = 0;
                    723:                     foreach (keys(%status)) {
                    724:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    725:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    726:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    727: 
                    728:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    729:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    730:                             $submitted = 0;
                    731:                         }
                    732:                     }
                    733:                     if (!$submitted && ($submitonly eq 'yes' ||
                    734:                                         $submitonly eq 'incorrect' ||
                    735:                                         $submitonly eq 'graded')) {
                    736:                         delete($classlist->{$student});
                    737:                         next;
                    738:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    739:                         delete($classlist->{$student});
                    740:                         next;
                    741:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    742:                         delete($classlist->{$student});
                    743:                         next;
                    744:                     }
                    745:                 }
                    746:             }
                    747:         }
1.205     matthew   748: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  749: 	if (&canview($section)) {
1.291     albertel  750: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  751: 		$sections{$section}++;
1.450     banghart  752: 		if ($classlist->{$student}) {
                    753: 		    $fullnames{$student}=$fullname;
                    754: 		}
1.103     albertel  755: 	    } else {
1.205     matthew   756: 		delete($classlist->{$student});
1.103     albertel  757: 	    }
                    758: 	} else {
1.205     matthew   759: 	    delete($classlist->{$student});
1.103     albertel  760: 	}
1.44      ng        761:     }
1.56      matthew   762:     my @sections = sort(keys(%sections));
                    763:     return ($classlist,\@sections,\%fullnames);
1.44      ng        764: }
                    765: 
1.103     albertel  766: sub canmodify {
                    767:     my ($sec)=@_;
                    768:     if ($perm{'mgr'}) {
                    769: 	if (!defined($perm{'mgr_section'})) {
                    770: 	    # can modify whole class
                    771: 	    return 1;
                    772: 	} else {
                    773: 	    if ($sec eq $perm{'mgr_section'}) {
                    774: 		#can modify the requested section
                    775: 		return 1;
                    776: 	    } else {
1.763     raeburn   777: 		# can't modify the requested section
1.103     albertel  778: 		return 0;
                    779: 	    }
                    780: 	}
                    781:     }
                    782:     #can't modify
                    783:     return 0;
                    784: }
                    785: 
                    786: sub canview {
                    787:     my ($sec)=@_;
                    788:     if ($perm{'vgr'}) {
                    789: 	if (!defined($perm{'vgr_section'})) {
1.763     raeburn   790: 	    # can view whole class
1.103     albertel  791: 	    return 1;
                    792: 	} else {
                    793: 	    if ($sec eq $perm{'vgr_section'}) {
1.763     raeburn   794: 		#can view the requested section
1.103     albertel  795: 		return 1;
                    796: 	    } else {
1.763     raeburn   797: 		# can't view the requested section
1.103     albertel  798: 		return 0;
                    799: 	    }
                    800: 	}
                    801:     }
1.763     raeburn   802:     #can't view
1.103     albertel  803:     return 0;
                    804: }
                    805: 
1.44      ng        806: #--- Retrieve the grade status of a student for all the parts
                    807: sub student_gradeStatus {
1.324     albertel  808:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  809:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        810:     my %partstatus = ();
                    811:     foreach (@$partlist) {
1.128     ng        812: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        813: 	$status              = 'nothing' if ($status eq '');
                    814: 	$partstatus{$_}      = $status;
                    815: 	my $subkey           = "resource.$_.submitted_by";
                    816: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    817:     }
                    818:     return %partstatus;
                    819: }
                    820: 
1.45      ng        821: # hidden form and javascript that calls the form
                    822: # Use by verifyscript and viewgrades
                    823: # Shows a student's view of problem and submission
                    824: sub jscriptNform {
1.324     albertel  825:     my ($symb) = @_;
1.442     banghart  826:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  827:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        828: 	'    function viewOneStudent(user,domain) {'."\n".
                    829: 	'	document.onestudent.student.value = user;'."\n".
                    830: 	'	document.onestudent.userdom.value = domain;'."\n".
                    831: 	'	document.onestudent.submit();'."\n".
                    832: 	'    }'."\n".
1.597     wenzelju  833: 	"\n");
1.45      ng        834:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  835: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  836: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        837: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    838: 	'<input type="hidden" name="student" value="" />'."\n".
                    839: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    840: 	'</form>'."\n";
                    841:     return $jscript;
                    842: }
1.39      ng        843: 
1.447     foxr      844: 
                    845: 
1.315     bowersj2  846: # Given the score (as a number [0-1] and the weight) what is the final
                    847: # point value? This function will round to the nearest tenth, third,
                    848: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  849: sub compute_points {
1.315     bowersj2  850:     my ($score, $weight) = @_;
                    851:     
                    852:     my $tolerance = .00001;
                    853:     my $points = $score * $weight;
                    854: 
                    855:     # Check for nearness to 1/x.
                    856:     my $check_for_nearness = sub {
                    857:         my ($factor) = @_;
                    858:         my $num = ($points * $factor) + $tolerance;
                    859:         my $floored_num = floor($num);
1.316     albertel  860:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  861:             return $floored_num / $factor;
                    862:         }
                    863:         return $points;
                    864:     };
                    865: 
                    866:     $points = $check_for_nearness->(10);
                    867:     $points = $check_for_nearness->(3);
                    868:     $points = $check_for_nearness->(4);
                    869:     
                    870:     return $points;
                    871: }
                    872: 
1.44      ng        873: #------------------ End of general use routines --------------------
1.87      www       874: 
                    875: #
                    876: # Find most similar essay
                    877: #
                    878: 
                    879: sub most_similar {
1.674     raeburn   880:     my ($uname,$udom,$symb,$uessay)=@_;
                    881: 
                    882:     unless ($symb) { return ''; }
                    883: 
                    884:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       885: 
                    886: # ignore spaces and punctuation
                    887: 
                    888:     $uessay=~s/\W+/ /gs;
                    889: 
1.282     www       890: # ignore empty submissions (occuring when only files are sent)
                    891: 
1.598     www       892:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       893: 
1.87      www       894: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       895:     my $limit=0.6;
1.87      www       896:     my $sname='';
                    897:     my $sdom='';
                    898:     my $scrsid='';
                    899:     my $sessay='';
                    900: # go through all essays ...
1.674     raeburn   901:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  902: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       903: # ... except the same student
1.426     albertel  904:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   905: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  906: 	$tessay=~s/\W+/ /gs;
1.87      www       907: # String similarity gives up if not even limit
1.426     albertel  908: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       909: # Found one
1.426     albertel  910: 	if ($tsimilar>$limit) {
                    911: 	    $limit=$tsimilar;
                    912: 	    $sname=$tname;
                    913: 	    $sdom=$tdom;
                    914: 	    $scrsid=$tcrsid;
1.674     raeburn   915: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  916: 	}
1.87      www       917:     }
1.88      www       918:     if ($limit>0.6) {
1.87      www       919:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    920:     } else {
                    921:        return ('','','','',0);
                    922:     }
                    923: }
                    924: 
1.44      ng        925: #-------------------------------------------------------------------
                    926: 
                    927: #------------------------------------ Receipt Verification Routines
1.45      ng        928: #
1.602     www       929: 
                    930: sub initialverifyreceipt {
1.608     www       931:    my ($request,$symb) = @_;
1.602     www       932:    &commonJSfunctions($request);
1.694     bisitz    933:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       934:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    935:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       936:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    937:         '<input type="hidden" name="command" value="verify" />'.
                    938:         "</form>\n";
1.602     www       939: }
                    940: 
1.44      ng        941: #--- Check whether a receipt number is valid.---
                    942: sub verifyreceipt {
1.766     raeburn   943:     my ($request,$symb) = @_;
1.44      ng        944: 
1.257     albertel  945:     my $courseid = $env{'request.course.id'};
1.184     www       946:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  947: 	$env{'form.receipt'};
1.44      ng        948:     $receipt     =~ s/[^\-\d]//g;
                    949: 
1.766     raeburn   950:     my $title =
1.487     albertel  951: 	'<h3><span class="LC_info">'.
1.605     www       952: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    953: 	'</span></h3>'."\n";
1.44      ng        954: 
                    955:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   956:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  957:     
                    958:     my $receiptparts=0;
1.390     albertel  959:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    960: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  961:     my $parts=['0'];
1.582     raeburn   962:     if ($receiptparts) {
                    963:         my $res_error; 
                    964:         ($parts)=&response_type($symb,\$res_error);
                    965:         if ($res_error) {
                    966:             return &navmap_errormsg();
                    967:         } 
                    968:     }
1.486     albertel  969:     
                    970:     my $header = 
                    971: 	&Apache::loncommon::start_data_table().
                    972: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  973: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    974: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    975: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  976:     if ($receiptparts) {
1.487     albertel  977: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  978:     }
                    979:     $header.=
                    980: 	&Apache::loncommon::end_data_table_header_row();
                    981: 
1.294     albertel  982:     foreach (sort 
                    983: 	     {
                    984: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    985: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    986: 		 }
                    987: 		 return $a cmp $b;
                    988: 	     } (keys(%$fullname))) {
1.44      ng        989: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  990: 	foreach my $part (@$parts) {
                    991: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  992: 		$contents.=
                    993: 		    &Apache::loncommon::start_data_table_row().
                    994: 		    '<td>&nbsp;'."\n".
1.177     albertel  995: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  996: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  997: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    998: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    999: 		if ($receiptparts) {
                   1000: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                   1001: 		}
1.486     albertel 1002: 		$contents.= 
                   1003: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel 1004: 		
                   1005: 		$matches++;
                   1006: 	    }
1.44      ng       1007: 	}
                   1008:     }
                   1009:     if ($matches == 0) {
1.584     bisitz   1010:         $string = $title
                   1011:                  .'<p class="LC_warning">'
                   1012:                  .&mt('No match found for the above receipt number.')
                   1013:                  .'</p>';
1.44      ng       1014:     } else {
1.324     albertel 1015: 	$string = &jscriptNform($symb).$title.
1.487     albertel 1016: 	    '<p>'.
1.584     bisitz   1017: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel 1018: 	    '</p>'.
1.486     albertel 1019: 	    $header.
                   1020: 	    $contents.
                   1021: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng       1022:     }
1.614     www      1023:     return $string;
1.44      ng       1024: }
                   1025: 
                   1026: #--- This is called by a number of programs.
                   1027: #--- Called from the Grading Menu - View/Grade an individual student
                   1028: #--- Also called directly when one clicks on the subm button 
                   1029: #    on the problem page.
1.30      ng       1030: sub listStudents {
1.773   ! raeburn  1031:     my ($request,$symb,$submitonly,$divforres) = @_;
1.49      albertel 1032: 
1.747     raeburn  1033:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel 1034:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   1035:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   1036:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart 1037:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www      1038:     unless ($submitonly) {
1.766     raeburn  1039:         $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.617     www      1040:     }
1.49      albertel 1041: 
1.632     www      1042:     my $result='';
1.623     www      1043:     my $res_error;
1.773   ! raeburn  1044:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
        !          1045: 
        !          1046:     my $table;
        !          1047:     if (ref($partlist) eq 'ARRAY') {
        !          1048:         if (scalar(@$partlist) > 1 ) {
        !          1049:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradesub',1);
        !          1050:         } elsif ($divforres) {
        !          1051:             $table = '<div style="padding:0;clear:both;margin:0;border:0"></div>';
        !          1052:         } else {
        !          1053:             $table = '<br clear="all" />';
        !          1054:         }
        !          1055:     }
1.49      albertel 1056: 
1.736     damieng  1057:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn  1058: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                   1059: 		'single'   => 'Please select the student before clicking on the Next button.',
                   1060: 	     );
1.736     damieng  1061:     &js_escape(\%js_lt);
1.597     wenzelju 1062:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng       1063:     function checkSelect(checkBox) {
                   1064: 	var ctr=0;
                   1065: 	var sense="";
                   1066: 	if (checkBox.length > 1) {
                   1067: 	    for (var i=0; i<checkBox.length; i++) {
                   1068: 		if (checkBox[i].checked) {
                   1069: 		    ctr++;
                   1070: 		}
                   1071: 	    }
1.736     damieng  1072: 	    sense = '$js_lt{'multiple'}';
1.110     ng       1073: 	} else {
                   1074: 	    if (checkBox.checked) {
                   1075: 		ctr = 1;
                   1076: 	    }
1.736     damieng  1077: 	    sense = '$js_lt{'single'}';
1.110     ng       1078: 	}
                   1079: 	if (ctr == 0) {
1.485     albertel 1080: 	    alert(sense);
1.110     ng       1081: 	    return false;
                   1082: 	}
                   1083: 	document.gradesub.submit();
                   1084:     }
                   1085: 
                   1086:     function reLoadList(formname) {
1.112     ng       1087: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1088: 	formname.command.value = 'submission';
                   1089: 	formname.submit();
                   1090:     }
1.45      ng       1091: LISTJAVASCRIPT
                   1092: 
1.118     ng       1093:     &commonJSfunctions($request);
1.41      ng       1094:     $request->print($result);
1.39      ng       1095: 
1.154     albertel 1096:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.773   ! raeburn  1097: 	"\n".$table;
        !          1098: 
1.561     bisitz   1099:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn  1100:     unless ($is_tool) {
                   1101:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   1102:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                   1103:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1104:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                   1105:                       .&Apache::lonhtmlcommon::row_closure();
                   1106:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                   1107:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                   1108:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                   1109:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                   1110:                       .&Apache::lonhtmlcommon::row_closure();
                   1111:     }
1.485     albertel 1112: 
1.442     banghart 1113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1114:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1115:     $env{'form.Status'} = $saveStatus;
1.745     raeburn  1116:     my %optiontext;
                   1117:     if ($is_tool) {
                   1118:         %optiontext = &Apache::lonlocal::texthash (
                   1119:                           lastonly => 'last transaction',
                   1120:                           last     => 'last transaction with details',
                   1121:                           datesub  => 'all transactions',
                   1122:                           all      => 'all transactions with details',
                   1123:                       );
                   1124:     } else {
                   1125:         %optiontext = &Apache::lonlocal::texthash (
                   1126:                           lastonly => 'last submission',
                   1127:                           last     => 'last submission with details',
                   1128:                           datesub  => 'all submissions',
                   1129:                           all      => 'all submissions with details',
                   1130:                       );
                   1131:     }
1.773   ! raeburn  1132:     my $submission_options =
1.592     bisitz   1133:         '<span class="LC_nobreak">'.
1.624     www      1134:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1135:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1136:         '<span class="LC_nobreak">'.
                   1137:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1138:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1139:         '<span class="LC_nobreak">'.
1.628     www      1140:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1141:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1142:         '<span class="LC_nobreak">'.
                   1143:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1144:         $optiontext{'all'}.'</label></span>';
                   1145:     my $viewtitle;
                   1146:     if ($is_tool) {
                   1147:         $viewtitle = &mt('View Transactions');
                   1148:     } else {
                   1149:         $viewtitle = &mt('View Submissions');
                   1150:     }
1.773   ! raeburn  1151:     my ($compmsg,$nocompmsg);
        !          1152:     $nocompmsg = ' checked="checked"';
        !          1153:     if ($numessay) {
        !          1154:         $compmsg = $nocompmsg;
        !          1155:         $nocompmsg = '';
        !          1156:     }
1.745     raeburn  1157:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1158:                   .$submission_options
1.773   ! raeburn  1159:                   .&Apache::lonhtmlcommon::row_closure()
        !          1160:                   .&Apache::lonhtmlcommon::row_title(&mt('Send Messages'))
        !          1161:                   .'<span class="LC_nobreak">'
        !          1162:                   .'<label><input type="radio" name="compmsg" value="0"'.$nocompmsg.' />'
        !          1163:                   .&mt('No').('&nbsp;'x2).'</label>'
        !          1164:                   .'<label><input type="radio" name="compmsg" value="1"'.$compmsg.' />'
        !          1165:                   .&mt('Yes').('&nbsp;'x2).'</label>'
1.561     bisitz   1166:                   .&Apache::lonhtmlcommon::row_closure();
                   1167: 
                   1168:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1169:                   .'<select name="increment">'
                   1170:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1171:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1172:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1173:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1.773   ! raeburn  1174:                   .'</select>';
1.485     albertel 1175:     $gradeTable .= 
1.432     banghart 1176:         &build_section_inputs().
1.45      ng       1177: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1178: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1179: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1.618     www      1180:     if (exists($env{'form.Status'})) {
1.561     bisitz   1181: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1182:     } else {
1.773   ! raeburn  1183:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
        !          1184:                       .&Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1.561     bisitz   1185:                       .&Apache::lonhtmlcommon::StatusOptions(
1.773   ! raeburn  1186:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);');
1.124     ng       1187:     }
1.773   ! raeburn  1188:     if ($numessay) {
        !          1189:         $gradeTable .= &Apache::lonhtmlcommon::row_closure()
        !          1190:                       .&Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
        !          1191:                       .'<input type="checkbox" name="checkPlag" checked="checked" />';
1.745     raeburn  1192:     }
1.773   ! raeburn  1193:     $gradeTable .= &Apache::lonhtmlcommon::row_closure(1)
        !          1194:                   .&Apache::lonhtmlcommon::end_pick_box();
1.745     raeburn  1195:     my $regrademsg;
                   1196:     if ($is_tool) {
                   1197:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
                   1198:     } else {
                   1199:         $regrademsg = &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.");
                   1200:     }
1.561     bisitz   1201:     $gradeTable .= '<p>'
1.745     raeburn  1202:                   .$regrademsg."\n"
1.561     bisitz   1203:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1204:                   .'</p>';
1.249     albertel 1205: 
                   1206: # checkall buttons
                   1207:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1208:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1209:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1210:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1211:     $gradeTable.=&check_buttons();
1.450     banghart 1212:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1213:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1214: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1215:     my $loop = 0;
                   1216:     while ($loop < 2) {
1.485     albertel 1217: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1218: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1219: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1220: 	    foreach my $part (sort(@$partlist)) {
                   1221: 		my $display_part=
                   1222: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1223: 		$gradeTable.=
                   1224: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1225: 	    }
1.301     albertel 1226: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1227: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1228: 	}
                   1229: 	$loop++;
1.126     ng       1230: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1231:     }
1.474     albertel 1232:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1233: 
1.45      ng       1234:     my $ctr = 0;
1.294     albertel 1235:     foreach my $student (sort 
                   1236: 			 {
                   1237: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1238: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1239: 			     }
                   1240: 			     return $a cmp $b;
                   1241: 			 }
                   1242: 			 (keys(%$fullname))) {
1.41      ng       1243: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1244: 
1.110     ng       1245: 	my %status = ();
1.301     albertel 1246: 
                   1247: 	if ($submitonly eq 'queued') {
                   1248: 	    my %queue_status = 
                   1249: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1250: 							$udom,$uname);
                   1251: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1252: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1253: 	}
                   1254: 
1.618     www      1255: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1256: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1257: 	    my $submitted = 0;
1.164     albertel 1258: 	    my $graded = 0;
1.248     albertel 1259: 	    my $incorrect = 0;
1.110     ng       1260: 	    foreach (keys(%status)) {
1.145     albertel 1261: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1262: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1263: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1264: 		
1.110     ng       1265: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1266: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1267: 		    $submitted = 0;
1.150     albertel 1268: 		    my ($part)=split(/\./,$partid);
1.110     ng       1269: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1270: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1271: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1272: 		}
1.41      ng       1273: 	    }
1.248     albertel 1274: 	    
1.156     albertel 1275: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1276: 				     $submitonly eq 'incorrect' ||
                   1277: 				     $submitonly eq 'graded'));
1.248     albertel 1278: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1279: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1280: 	}
1.34      ng       1281: 
1.45      ng       1282: 	$ctr++;
1.249     albertel 1283: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1284:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1285: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1286: 	    if ($ctr%2 ==1) {
                   1287: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1288: 	    }
1.126     ng       1289: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1290:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1291:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1292: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1293: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1294: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1295: 
1.618     www      1296: 	    if ($submitonly ne 'all') {
1.524     raeburn  1297: 		foreach (sort(keys(%status))) {
1.485     albertel 1298: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1299: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1300: 		}
1.41      ng       1301: 	    }
1.126     ng       1302: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1303: 	    if ($ctr%2 ==0) {
                   1304: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1305: 	    }
1.41      ng       1306: 	}
                   1307:     }
1.110     ng       1308:     if ($ctr%2 ==1) {
1.126     ng       1309: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1310: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1311: 		foreach (@$partlist) {
                   1312: 		    $gradeTable.='<td>&nbsp;</td>';
                   1313: 		}
1.301     albertel 1314: 	    } elsif ($submitonly eq 'queued') {
                   1315: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1316: 	    }
1.474     albertel 1317: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1318:     }
                   1319: 
1.474     albertel 1320:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1321:         '<input type="button" '.
                   1322:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1323:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1324:     if ($ctr == 0) {
1.96      albertel 1325: 	my $num_students=(scalar(keys(%$fullname)));
                   1326: 	if ($num_students eq 0) {
1.485     albertel 1327: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1328: 	} else {
1.171     albertel 1329: 	    my $submissions='submissions';
                   1330: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1331: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1332: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1333: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1334: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1335: 		    $num_students).
                   1336: 		'</span><br />';
1.96      albertel 1337: 	}
1.46      ng       1338:     } elsif ($ctr == 1) {
1.474     albertel 1339: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1340:     }
                   1341:     $request->print($gradeTable);
1.44      ng       1342:     return '';
1.10      ng       1343: }
                   1344: 
1.44      ng       1345: #---- Called from the listStudents routine
1.249     albertel 1346: 
                   1347: sub check_script {
1.766     raeburn  1348:     my ($form,$type) = @_;
                   1349:     my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1350:     function checkall() {
                   1351:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1352:             ele = document.forms.'.$form.'.elements[i];
                   1353:             if (ele.name == "'.$type.'") {
                   1354:             document.forms.'.$form.'.elements[i].checked=true;
                   1355:                                        }
                   1356:         }
                   1357:     }
                   1358: 
                   1359:     function checksec() {
                   1360:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1361:             ele = document.forms.'.$form.'.elements[i];
                   1362:            string = document.forms.'.$form.'.chksec.value;
                   1363:            if
                   1364:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1365:               document.forms.'.$form.'.elements[i].checked=true;
                   1366:             }
                   1367:         }
                   1368:     }
                   1369: 
                   1370: 
                   1371:     function uncheckall() {
                   1372:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1373:             ele = document.forms.'.$form.'.elements[i];
                   1374:             if (ele.name == "'.$type.'") {
                   1375:             document.forms.'.$form.'.elements[i].checked=false;
                   1376:                                        }
                   1377:         }
                   1378:     }
                   1379: 
1.597     wenzelju 1380: '."\n");
1.249     albertel 1381:     return $chkallscript;
                   1382: }
                   1383: 
                   1384: sub check_buttons {
1.485     albertel 1385:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1386:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1387:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1388:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1389:     return $buttons;
                   1390: }
                   1391: 
1.44      ng       1392: #     Displays the submissions for one student or a group of students
1.34      ng       1393: sub processGroup {
1.766     raeburn  1394:     my ($request,$symb) = @_;
1.41      ng       1395:     my $ctr        = 0;
1.155     albertel 1396:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1397:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1398: 
1.396     banghart 1399:     foreach my $student (@stuchecked) {
                   1400: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1401: 	$env{'form.student'}        = $uname;
                   1402: 	$env{'form.userdom'}        = $udom;
                   1403: 	$env{'form.fullname'}       = $fullname;
1.619     www      1404: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1405: 	$ctr++;
                   1406:     }
                   1407:     return '';
1.35      ng       1408: }
1.34      ng       1409: 
1.44      ng       1410: #------------------------------------------------------------------------------------
                   1411: #
                   1412: #-------------------------- Next few routines handles grading by student, essentially
                   1413: #                           handles essay response type problem/part
                   1414: #
                   1415: #--- Javascript to handle the submission page functionality ---
                   1416: sub sub_page_js {
                   1417:     my $request = shift;
1.736     damieng  1418:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1419:     &js_escape(\$alertmsg);
1.597     wenzelju 1420:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1421:     function updateRadio(formname,id,weight) {
1.125     ng       1422: 	var gradeBox = formname["GD_BOX"+id];
                   1423: 	var radioButton = formname["RADVAL"+id];
                   1424: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1425: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1426: 	gradeBox.value = pts;
                   1427: 	var resetbox = false;
                   1428: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1429: 	    alert("$alertmsg"+pts);
1.71      ng       1430: 	    for (var i=0; i<radioButton.length; i++) {
                   1431: 		if (radioButton[i].checked) {
                   1432: 		    gradeBox.value = i;
                   1433: 		    resetbox = true;
                   1434: 		}
                   1435: 	    }
                   1436: 	    if (!resetbox) {
                   1437: 		formtextbox.value = "";
                   1438: 	    }
                   1439: 	    return;
1.44      ng       1440: 	}
1.71      ng       1441: 
                   1442: 	if (pts > weight) {
                   1443: 	    var resp = confirm("You entered a value ("+pts+
                   1444: 			       ") greater than the weight for the part. Accept?");
                   1445: 	    if (resp == false) {
1.125     ng       1446: 		gradeBox.value = oldpts;
1.71      ng       1447: 		return;
                   1448: 	    }
1.44      ng       1449: 	}
1.13      albertel 1450: 
1.71      ng       1451: 	for (var i=0; i<radioButton.length; i++) {
                   1452: 	    radioButton[i].checked=false;
                   1453: 	    if (pts == i && pts != "") {
                   1454: 		radioButton[i].checked=true;
                   1455: 	    }
                   1456: 	}
                   1457: 	updateSelect(formname,id);
1.125     ng       1458: 	formname["stores"+id].value = "0";
1.41      ng       1459:     }
1.5       albertel 1460: 
1.72      ng       1461:     function writeBox(formname,id,pts) {
1.125     ng       1462: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1463: 	if (checkSolved(formname,id) == 'update') {
                   1464: 	    gradeBox.value = pts;
                   1465: 	} else {
1.125     ng       1466: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1467: 	    gradeBox.value = oldpts;
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;
1.72      ng       1471: 		if (i == oldpts) {
1.71      ng       1472: 		    radioButton[i].checked=true;
                   1473: 		}
                   1474: 	    }
1.41      ng       1475: 	}
1.125     ng       1476: 	formname["stores"+id].value = "0";
1.71      ng       1477: 	updateSelect(formname,id);
                   1478: 	return;
1.41      ng       1479:     }
1.44      ng       1480: 
1.71      ng       1481:     function clearRadBox(formname,id) {
                   1482: 	if (checkSolved(formname,id) == 'noupdate') {
                   1483: 	    updateSelect(formname,id);
                   1484: 	    return;
                   1485: 	}
1.125     ng       1486: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1487: 	for (var i=0; i<gradeSelect.length; i++) {
                   1488: 	    if (gradeSelect[i].selected) {
                   1489: 		var selectx=i;
                   1490: 	    }
                   1491: 	}
1.125     ng       1492: 	var stores = formname["stores"+id];
1.71      ng       1493: 	if (selectx == stores.value) { return };
1.125     ng       1494: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1495: 	gradeBox.value = "";
1.125     ng       1496: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1497: 	for (var i=0; i<radioButton.length; i++) {
                   1498: 	    radioButton[i].checked=false;
                   1499: 	}
                   1500: 	stores.value = selectx;
                   1501:     }
1.5       albertel 1502: 
1.71      ng       1503:     function checkSolved(formname,id) {
1.125     ng       1504: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1505: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1506: 	    if (!reply) {return "noupdate";}
1.120     ng       1507: 	    formname.overRideScore.value = 'yes';
1.41      ng       1508: 	}
1.71      ng       1509: 	return "update";
1.13      albertel 1510:     }
1.71      ng       1511: 
                   1512:     function updateSelect(formname,id) {
1.125     ng       1513: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1514: 	return;
1.41      ng       1515:     }
1.33      ng       1516: 
1.121     ng       1517: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1518:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1519: 	formname.gradeOpt.value = val;
1.71      ng       1520: 	if (val == "Save & Next") {
                   1521: 	    for (i=0;i<=total;i++) {
                   1522: 		for (j=0;j<parttot;j++) {
1.125     ng       1523: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1524: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1525: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1526: 			if (points == "") {
1.125     ng       1527: 			    var name = formname["name"+i].value;
1.129     ng       1528: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1529: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1530: 					       ", part "+partid+". Continue?");
1.71      ng       1531: 			    if (resp == false) {
1.125     ng       1532: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1533: 				return false;
                   1534: 			    }
                   1535: 			}
                   1536: 		    }
                   1537: 		}
                   1538: 	    }
                   1539: 	}
1.120     ng       1540: 	formname.submit();
                   1541:     }
                   1542: 
1.71      ng       1543: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1544:     function checkSubmitPage(formname,total) {
                   1545: 	noscore = new Array(100);
                   1546: 	var ptr = 0;
                   1547: 	for (i=1;i<total;i++) {
1.125     ng       1548: 	    var partid = formname["q_"+i].value;
1.127     ng       1549: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1550: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1551: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1552: 		if (points == "" && status != "correct_by_student") {
                   1553: 		    noscore[ptr] = i;
                   1554: 		    ptr++;
                   1555: 		}
                   1556: 	    }
                   1557: 	}
                   1558: 	if (ptr != 0) {
                   1559: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1560: 	    var prolist = "";
                   1561: 	    if (ptr == 1) {
                   1562: 		prolist = noscore[0];
                   1563: 	    } else {
                   1564: 		var i = 0;
                   1565: 		while (i < ptr-1) {
                   1566: 		    prolist += noscore[i]+", ";
                   1567: 		    i++;
                   1568: 		}
                   1569: 		prolist += "and "+noscore[i];
                   1570: 	    }
                   1571: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1572: 	    if (resp == false) {
                   1573: 		return false;
                   1574: 	    }
                   1575: 	}
1.45      ng       1576: 
1.71      ng       1577: 	formname.submit();
                   1578:     }
                   1579: SUBJAVASCRIPT
                   1580: }
1.45      ng       1581: 
1.773   ! raeburn  1582: #--- javascript for grading message center
        !          1583: sub sub_grademessage_js {
1.71      ng       1584:     my $request = shift;
1.80      ng       1585:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1586:     &commonJSfunctions($request);
1.350     albertel 1587: 
1.629     www      1588:     my $inner_js_msg_central= (<<INNERJS);
                   1589: <script type="text/javascript">
1.350     albertel 1590:     function checkInput() {
                   1591:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1592:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1593:       var usrctr = document.msgcenter.usrctr.value;
                   1594:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1595:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1596: 
                   1597:       var msgchk = "";
                   1598:       if (document.msgcenter.subchk.checked) {
                   1599:          msgchk = "msgsub,";
                   1600:       }
                   1601:       var includemsg = 0;
                   1602:       for (var i=1; i<=nmsg; i++) {
                   1603:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1604:           var frmmsg = document.msgcenter["msg"+i];
                   1605:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1606:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1607:           showflg.value = "1";
                   1608:           var chkbox = document.msgcenter["msgn"+i];
                   1609:           if (chkbox.checked) {
                   1610:              msgchk += "savemsg"+i+",";
                   1611:              includemsg = 1;
                   1612:           }
                   1613:       }
                   1614:       if (document.msgcenter.newmsgchk.checked) {
                   1615:          msgchk += "newmsg"+usrctr;
                   1616:          includemsg = 1;
                   1617:       }
                   1618:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1619:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1620:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1621:       includemsg.value = msgchk;
                   1622: 
                   1623:       self.close()
                   1624: 
                   1625:     }
1.629     www      1626: </script>
1.350     albertel 1627: INNERJS
                   1628: 
1.773   ! raeburn  1629:     my $start_page_msg_central =
1.351     albertel 1630:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1631: 				       {'js_ready'  => 1,
                   1632: 					'only_body' => 1,
                   1633: 					'bgcolor'   =>'#FFFFFF',});
1.773   ! raeburn  1634:     my $end_page_msg_central =
1.350     albertel 1635: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1636: 
1.219     www      1637:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1638:     $docopen=~s/^document\.//;
1.773   ! raeburn  1639: 
1.736     damieng  1640:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1641:                 comp => 'Compose Message for: ',
                   1642:                 incl => 'Include',
1.656     raeburn  1643:                 type => 'Type',
1.652     raeburn  1644:                 subj => 'Subject',
                   1645:                 mesa => 'Message',
                   1646:                 new  => 'New',
                   1647:                 save => 'Save',
                   1648:                 canc => 'Cancel',
                   1649:              );
1.736     damieng  1650:     &html_escape(\%html_js_lt);
                   1651:     &js_escape(\%html_js_lt);
1.597     wenzelju 1652:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1653: 
1.44      ng       1654: //===================== Script to view submitted by ==================
                   1655:   function viewSubmitter(submitter) {
                   1656:     document.SCORE.refresh.value = "on";
                   1657:     document.SCORE.NCT.value = "1";
                   1658:     document.SCORE.unamedom0.value = submitter;
                   1659:     document.SCORE.submit();
                   1660:     return;
                   1661:   }
                   1662: 
                   1663: //====================== Script for composing message ==============
1.80      ng       1664:    // preload images
                   1665:    img1 = new Image();
                   1666:    img1.src = "$iconpath/mailbkgrd.gif";
                   1667:    img2 = new Image();
                   1668:    img2.src = "$iconpath/mailto.gif";
                   1669: 
1.44      ng       1670:   function msgCenter(msgform,usrctr,fullname) {
                   1671:     var Nmsg  = msgform.savemsgN.value;
                   1672:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1673:     var subject = msgform.msgsub.value;
1.127     ng       1674:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1675:     re = /msgsub/;
                   1676:     var shwsel = "";
                   1677:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1678:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1679:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1680:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1681: 	var testmsg = "savemsg"+i+",";
                   1682: 	re = new RegExp(testmsg,"g");
1.44      ng       1683: 	shwsel = "";
                   1684: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1685: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1686: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1687: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1688: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1689:     }
1.125     ng       1690:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1691:     shwsel = "";
                   1692:     re = /newmsg/;
                   1693:     if (re.test(msgchk)) { shwsel = "checked" }
                   1694:     newMsg(newmsg,shwsel);
                   1695:     msgTail(); 
                   1696:     return;
                   1697:   }
                   1698: 
1.123     ng       1699:   function checkEntities(strx) {
                   1700:     if (strx.length == 0) return strx;
                   1701:     var orgStr = ["&", "<", ">", '"']; 
                   1702:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1703:     var counter = 0;
                   1704:     while (counter < 4) {
                   1705: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1706: 	counter++;
                   1707:     }
                   1708:     return strx;
                   1709:   }
                   1710: 
                   1711:   function strReplace(strx, orgStr, newStr) {
                   1712:     return strx.split(orgStr).join(newStr);
                   1713:   }
                   1714: 
1.44      ng       1715:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1716:     var height = 70*Nmsg+250;
1.44      ng       1717:     if (height > 600) {
                   1718: 	height = 600;
                   1719:     }
1.118     ng       1720:     var xpos = (screen.width-600)/2;
                   1721:     xpos = (xpos < 0) ? '0' : xpos;
                   1722:     var ypos = (screen.height-height)/2-30;
                   1723:     ypos = (ypos < 0) ? '0' : ypos;
                   1724: 
1.668     www      1725:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1726:     pWin.focus();
                   1727:     pDoc = pWin.document;
1.219     www      1728:     pDoc.$docopen;
1.351     albertel 1729:     pDoc.write('$start_page_msg_central');
1.76      ng       1730: 
                   1731:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1732:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1733:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1734: 
1.676     golterma 1735:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1736:     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       1737: }
                   1738:     function displaySubject(msg,shwsel) {
1.76      ng       1739:     pDoc = pWin.document;
1.676     golterma 1740:     pDoc.write("<tr>");
                   1741:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1742:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1743:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1744: }
                   1745: 
1.72      ng       1746:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1747:     pDoc = pWin.document;
1.676     golterma 1748:     pDoc.write("<tr>");
                   1749:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1750:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1751:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1752: }
                   1753: 
                   1754:   function newMsg(newmsg,shwsel) {
1.76      ng       1755:     pDoc = pWin.document;
1.676     golterma 1756:     pDoc.write("<tr>");
                   1757:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1758:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1759:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1760: }
                   1761: 
                   1762:   function msgTail() {
1.76      ng       1763:     pDoc = pWin.document;
1.676     golterma 1764:     //pDoc.write("<\\/table>");
1.465     albertel 1765:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1766:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1767:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1768:     pDoc.write("<\\/form>");
1.351     albertel 1769:     pDoc.write('$end_page_msg_central');
1.128     ng       1770:     pDoc.close();
1.44      ng       1771: }
                   1772: 
1.773   ! raeburn  1773: SUBJAVASCRIPT
        !          1774: }
        !          1775: 
        !          1776: #--- javascript for essay type problem --
        !          1777: sub sub_page_kw_js {
        !          1778:     my $request = shift;
        !          1779: 
        !          1780:     unless ($env{'form.compmsg'}) {
        !          1781:         &commonJSfunctions($request);
        !          1782:     }
        !          1783: 
        !          1784:     my $inner_js_highlight_central= (<<INNERJS);
        !          1785: <script type="text/javascript">
        !          1786:     function updateChoice(flag) {
        !          1787:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
        !          1788:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
        !          1789:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
        !          1790:       opener.document.SCORE.refresh.value = "on";
        !          1791:       if (opener.document.SCORE.keywords.value!=""){
        !          1792:          opener.document.SCORE.submit();
        !          1793:       }
        !          1794:       self.close()
        !          1795:     }
        !          1796: </script>
        !          1797: INNERJS
        !          1798: 
        !          1799:     my $start_page_highlight_central =
        !          1800:         &Apache::loncommon::start_page('Highlight Central',
        !          1801:                                        $inner_js_highlight_central,
        !          1802:                                        {'js_ready'  => 1,
        !          1803:                                         'only_body' => 1,
        !          1804:                                         'bgcolor'   =>'#FFFFFF',});
        !          1805:     my $end_page_highlight_central =
        !          1806:         &Apache::loncommon::end_page({'js_ready' => 1});
        !          1807: 
        !          1808:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
        !          1809:     $docopen=~s/^document\.//;
        !          1810: 
        !          1811:     my %js_lt = &Apache::lonlocal::texthash(
        !          1812:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
        !          1813:                 plse => 'Please select a word or group of words from document and then click this link.',
        !          1814:                 adds => 'Add selection to keyword list? Edit if desired.',
        !          1815:                 col1 => 'red',
        !          1816:                 col2 => 'green',
        !          1817:                 col3 => 'blue',
        !          1818:                 siz1 => 'normal',
        !          1819:                 siz2 => '+1',
        !          1820:                 siz3 => '+2',
        !          1821:                 sty1 => 'normal',
        !          1822:                 sty2 => 'italic',
        !          1823:                 sty3 => 'bold',
        !          1824:              );
        !          1825:     my %html_js_lt = &Apache::lonlocal::texthash(
        !          1826:                 save => 'Save',
        !          1827:                 canc => 'Cancel',
        !          1828:                 kehi => 'Keyword Highlight Options',
        !          1829:                 txtc => 'Text Color',
        !          1830:                 font => 'Font Size',
        !          1831:                 fnst => 'Font Style',
        !          1832:              );
        !          1833:     &js_escape(\%js_lt);
        !          1834:     &html_escape(\%html_js_lt);
        !          1835:     &js_escape(\%html_js_lt);
        !          1836:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
        !          1837: 
        !          1838: //===================== Show list of keywords ====================
        !          1839:   function keywords(formname) {
        !          1840:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
        !          1841:     if (nret==null) return;
        !          1842:     formname.keywords.value = nret;
        !          1843: 
        !          1844:     if (formname.keywords.value != "") {
        !          1845:         formname.refresh.value = "on";
        !          1846:         formname.submit();
        !          1847:     }
        !          1848:     return;
        !          1849:   }
        !          1850: 
        !          1851: //===================== Script to add keyword(s) ==================
        !          1852:   function getSel() {
        !          1853:     if (document.getSelection) txt = document.getSelection();
        !          1854:     else if (document.selection) txt = document.selection.createRange().text;
        !          1855:     else return;
        !          1856:     if (typeof(txt) != 'string') {
        !          1857:         txt = String(txt);
        !          1858:     }
        !          1859:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
        !          1860:     if (cleantxt=="") {
        !          1861:         alert("$js_lt{'plse'}");
        !          1862:         return;
        !          1863:     }
        !          1864:     var nret = prompt("$js_lt{'adds'}",cleantxt);
        !          1865:     if (nret==null) return;
        !          1866:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
        !          1867:     if (document.SCORE.keywords.value != "") {
        !          1868:         document.SCORE.refresh.value = "on";
        !          1869:         document.SCORE.submit();
        !          1870:     }
        !          1871:     return;
        !          1872:   }
        !          1873: 
1.44      ng       1874: //====================== Script for keyword highlight options ==============
                   1875:   function kwhighlight() {
                   1876:     var kwclr    = document.SCORE.kwclr.value;
                   1877:     var kwsize   = document.SCORE.kwsize.value;
                   1878:     var kwstyle  = document.SCORE.kwstyle.value;
                   1879:     var redsel = "";
                   1880:     var grnsel = "";
                   1881:     var blusel = "";
1.736     damieng  1882:     var txtcol1 = "$js_lt{'col1'}";
                   1883:     var txtcol2 = "$js_lt{'col2'}";
                   1884:     var txtcol3 = "$js_lt{'col3'}";
                   1885:     var txtsiz1 = "$js_lt{'siz1'}";
                   1886:     var txtsiz2 = "$js_lt{'siz2'}";
                   1887:     var txtsiz3 = "$js_lt{'siz3'}";
                   1888:     var txtsty1 = "$js_lt{'sty1'}";
                   1889:     var txtsty2 = "$js_lt{'sty2'}";
                   1890:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1891:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1892:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1893:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1894:     var sznsel = "";
                   1895:     var sz1sel = "";
                   1896:     var sz2sel = "";
1.718     bisitz   1897:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1898:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1899:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1900:     var synsel = "";
                   1901:     var syisel = "";
                   1902:     var sybsel = "";
1.718     bisitz   1903:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1904:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1905:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1906:     highlightCentral();
1.718     bisitz   1907:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1908:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1909:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1910:     highlightend();
                   1911:     return;
                   1912:   }
                   1913: 
                   1914:   function highlightCentral() {
1.76      ng       1915: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1916:     var xpos = (screen.width-400)/2;
                   1917:     xpos = (xpos < 0) ? '0' : xpos;
                   1918:     var ypos = (screen.height-330)/2-30;
                   1919:     ypos = (ypos < 0) ? '0' : ypos;
                   1920: 
1.206     albertel 1921:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1922:     hwdWin.focus();
                   1923:     var hDoc = hwdWin.document;
1.219     www      1924:     hDoc.$docopen;
1.351     albertel 1925:     hDoc.write('$start_page_highlight_central');
1.76      ng       1926:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1927:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1928: 
1.718     bisitz   1929:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1930:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1931:   }
                   1932: 
                   1933:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1934:     var hDoc = hwdWin.document;
1.718     bisitz   1935:     hDoc.write("<tr>");
1.76      ng       1936:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1937:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1938:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1939:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1940:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1941:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1942:     hDoc.write("<\\/tr>");
1.44      ng       1943:   }
                   1944: 
                   1945:   function highlightend() { 
1.76      ng       1946:     var hDoc = hwdWin.document;
1.718     bisitz   1947:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1948:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1949:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1950:     hDoc.write("<\\/form>");
1.351     albertel 1951:     hDoc.write('$end_page_highlight_central');
1.128     ng       1952:     hDoc.close();
1.44      ng       1953:   }
                   1954: 
                   1955: SUBJAVASCRIPT
                   1956: }
                   1957: 
1.349     albertel 1958: sub get_increment {
1.348     bowersj2 1959:     my $increment = $env{'form.increment'};
                   1960:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1961:         $increment != .1) {
                   1962:         $increment = 1;
                   1963:     }
                   1964:     return $increment;
                   1965: }
                   1966: 
1.585     bisitz   1967: sub gradeBox_start {
                   1968:     return (
                   1969:         &Apache::loncommon::start_data_table()
                   1970:        .&Apache::loncommon::start_data_table_header_row()
                   1971:        .'<th>'.&mt('Part').'</th>'
                   1972:        .'<th>'.&mt('Points').'</th>'
                   1973:        .'<th>&nbsp;</th>'
                   1974:        .'<th>'.&mt('Assign Grade').'</th>'
                   1975:        .'<th>'.&mt('Weight').'</th>'
                   1976:        .'<th>'.&mt('Grade Status').'</th>'
                   1977:        .&Apache::loncommon::end_data_table_header_row()
                   1978:     );
                   1979: }
                   1980: 
                   1981: sub gradeBox_end {
                   1982:     return (
                   1983:         &Apache::loncommon::end_data_table()
                   1984:     );
                   1985: }
1.71      ng       1986: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1987: sub gradeBox {
1.322     albertel 1988:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1989:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1990: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1991:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1992:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1993:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1994:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1995:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1996: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1997:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1998:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1999:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2000: 				       [$partid]);
                   2001:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  2002:     if ($last_resets{$partid}) {
                   2003:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   2004:     }
1.695     bisitz   2005:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       2006:     my $ctr = 0;
1.348     bowersj2 2007:     my $thisweight = 0;
1.349     albertel 2008:     my $increment = &get_increment();
1.485     albertel 2009: 
                   2010:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 2011:     while ($thisweight<=$wgt) {
1.532     bisitz   2012: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2013:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 2014: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 2015: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 2016: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 2017:         $thisweight += $increment;
1.71      ng       2018: 	$ctr++;
                   2019:     }
1.485     albertel 2020:     $radio.='</tr></table>';
                   2021: 
                   2022:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       2023: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   2024: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       2025: 	$wgt.')" /></td>'."\n";
1.485     albertel 2026:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       2027: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   2028: 	' </td>'."\n";
                   2029:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   2030: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       2031:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 2032: 	$line.='<option></option>'.
                   2033: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       2034:     } else {
1.485     albertel 2035: 	$line.='<option selected="selected"></option>'.
                   2036: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       2037:     }
1.485     albertel 2038:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   2039: 
                   2040: 
                   2041:     $result .= 
1.695     bisitz   2042: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   2043:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   2044:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       2045:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   2046: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   2047: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  2048: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   2049:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   2050:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   2051:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   2052:         $aggtries.'" />'."\n";
1.582     raeburn  2053:     my $res_error;
                   2054:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   2055:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  2056:     if ($res_error) {
                   2057:         return &navmap_errormsg();
                   2058:     }
1.318     banghart 2059:     return $result;
                   2060: }
1.322     albertel 2061: 
                   2062: sub handback_box {
1.623     www      2063:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1.773   ! raeburn  2064:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,$res_error_pointer);
        !          2065:     return unless ($numessay);
1.323     banghart 2066:     my (@respids);
1.652     raeburn  2067:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 2068:     foreach my $part_response_id (@part_response_id) {
                   2069:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 2070:         if ($part eq $partid) {
1.375     albertel 2071:             push(@respids,$resp);
1.323     banghart 2072:         }
                   2073:     }
1.318     banghart 2074:     my $result;
1.323     banghart 2075:     foreach my $respid (@respids) {
1.322     albertel 2076: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   2077: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   2078: 	next if (!@$files);
1.654     raeburn  2079: 	my $file_counter = 0;
1.313     banghart 2080: 	foreach my $file (@$files) {
1.368     banghart 2081: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  2082:                 $file_counter++;
1.368     banghart 2083:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  2084:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 2085:     	        $file_disp = "$name.$ext";
                   2086:     	        $file = $file_path.$file_disp;
                   2087:     	        $result.=&mt('Return commented version of [_1] to student.',
                   2088:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   2089:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  2090:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 2091: 	    }
1.322     albertel 2092: 	}
1.654     raeburn  2093:         if ($file_counter) {
                   2094:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   2095:                        '<span class="LC_info">'.
                   2096:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   2097:         }
1.313     banghart 2098:     }
1.318     banghart 2099:     return $result;    
1.71      ng       2100: }
1.44      ng       2101: 
1.58      albertel 2102: sub show_problem {
1.382     albertel 2103:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 2104:     my $rendered;
1.382     albertel 2105:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 2106:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 2107:     if ($mode eq 'both' or $mode eq 'text') {
                   2108: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 2109: 						       $env{'request.course.id'},
                   2110: 						       undef,\%form);
1.144     albertel 2111:     }
1.58      albertel 2112:     if ($removeform) {
                   2113: 	$rendered=~s|<form(.*?)>||g;
                   2114: 	$rendered=~s|</form>||g;
1.374     albertel 2115: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 2116:     }
1.144     albertel 2117:     my $companswer;
                   2118:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 2119: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 2120: 	$companswer=
                   2121: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   2122: 						    $env{'request.course.id'},
                   2123: 						    %form);
1.144     albertel 2124:     }
1.58      albertel 2125:     if ($removeform) {
                   2126: 	$companswer=~s|<form(.*?)>||g;
                   2127: 	$companswer=~s|</form>||g;
1.144     albertel 2128: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 2129:     }
1.671     raeburn  2130:     my $renderheading = &mt('View of the problem');
                   2131:     my $answerheading = &mt('Correct answer');
                   2132:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   2133:         my $stu_fullname = $env{'form.fullname'};
                   2134:         if ($stu_fullname eq '') {
                   2135:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2136:         }
                   2137:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   2138:         if ($forwhom ne '') {
                   2139:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   2140:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   2141:         }
                   2142:     }
1.468     albertel 2143:     $rendered=
1.588     bisitz   2144:         '<div class="LC_Box">'
1.671     raeburn  2145:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   2146:        .$rendered
                   2147:        .'</div>';
1.468     albertel 2148:     $companswer=
1.588     bisitz   2149:         '<div class="LC_Box">'
1.671     raeburn  2150:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   2151:        .$companswer
                   2152:        .'</div>';
1.468     albertel 2153:     my $result;
1.144     albertel 2154:     if ($mode eq 'both') {
1.588     bisitz   2155:         $result=$rendered.$companswer;
1.144     albertel 2156:     } elsif ($mode eq 'text') {
1.588     bisitz   2157:         $result=$rendered;
1.144     albertel 2158:     } elsif ($mode eq 'answer') {
1.588     bisitz   2159:         $result=$companswer;
1.144     albertel 2160:     }
1.71      ng       2161:     return $result;
1.58      albertel 2162: }
1.397     albertel 2163: 
1.396     banghart 2164: sub files_exist {
                   2165:     my ($r, $symb) = @_;
                   2166:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2167:     foreach my $student (@students) {
                   2168:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2169:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2170: 					      $udom,$uname);
1.396     banghart 2171:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2172:         foreach my $submission (@$string) {
                   2173:             my ($partid,$respid) =
                   2174: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2175:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2176: 					   \%record);
                   2177:             return 1 if (@$files);
1.396     banghart 2178:         }
                   2179:     }
1.397     albertel 2180:     return 0;
1.396     banghart 2181: }
1.397     albertel 2182: 
1.394     banghart 2183: sub download_all_link {
                   2184:     my ($r,$symb) = @_;
1.621     www      2185:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2186:         $r->print(&mt('There are currently no submitted documents.'));
                   2187:         return;
1.621     www      2188:     }
1.395     albertel 2189:     my $all_students = 
                   2190: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2191: 
                   2192:     my $parts =
                   2193: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2194: 
1.394     banghart 2195:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2196:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2197:                              'cgi.'.$identifier.'.symb' => $symb,
                   2198:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2199:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2200: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2201:     return;
                   2202: }
                   2203: 
                   2204: sub submit_download_link {
                   2205:     my ($request,$symb) = @_;
                   2206:     if (!$symb) { return ''; }
1.750     raeburn  2207:     my $res_error;
1.773   ! raeburn  2208:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
        !          2209:         &response_type($symb,\$res_error);
        !          2210:     if ($res_error) {
        !          2211:         $request->print(&mt('An error occurred retrieving response types'));
        !          2212:         return;
        !          2213:     }
        !          2214:     unless ($numessay) {
        !          2215:         $request->print(&mt('No essayresponse items found'));
        !          2216:         return;
1.750     raeburn  2217:     }
1.773   ! raeburn  2218:     my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
        !          2219:     if (@chosenparts) {
        !          2220:         $request->print(&showResourceInfo($symb,$partlist,$responseType,
        !          2221:                                           undef,undef,1));
1.750     raeburn  2222:     }
1.773   ! raeburn  2223:     if ($numessay) {
1.750     raeburn  2224:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2225:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2226:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2227:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2228:         if (ref($fullname) eq 'HASH') {
                   2229:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2230:             if (@students) {
                   2231:                 @{$env{'form.stuinfo'}} = @students;
1.773   ! raeburn  2232:                 if ($numdropbox) {
1.750     raeburn  2233:                     &download_all_link($request,$symb);
1.773   ! raeburn  2234:                 } else {
        !          2235:                     $request->print(&mt('No essayrespose items with dropbox found'));
1.750     raeburn  2236:                 }
1.773   ! raeburn  2237: # FIXME Need a mechanism to download essays, i.e., if $numessay > $numdropbox
1.750     raeburn  2238: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2239:             } else {
                   2240:                 $request->print(&mt('No students match the criteria you selected'));
                   2241:             }
                   2242:         } else {
                   2243:             $request->print(&mt('Could not retrieve student information'));
                   2244:         }
                   2245:     } else {
                   2246:         $request->print(&mt('No essayresponse items found'));
                   2247:     }
                   2248:     return;
1.394     banghart 2249: }
1.395     albertel 2250: 
1.432     banghart 2251: sub build_section_inputs {
                   2252:     my $section_inputs;
                   2253:     if ($env{'form.section'} eq '') {
                   2254:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2255:     } else {
                   2256:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2257:         foreach my $section (@sections) {
1.432     banghart 2258:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2259:         }
                   2260:     }
                   2261:     return $section_inputs;
                   2262: }
                   2263: 
1.44      ng       2264: # --------------------------- show submissions of a student, option to grade 
                   2265: sub submission {
1.773   ! raeburn  2266:     my ($request,$counter,$total,$symb,$divforres,$calledby) = @_;
1.257     albertel 2267:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2268:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2269:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2270:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2271: 
1.324     albertel 2272:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.773   ! raeburn  2273:     my $probtitle=&Apache::lonnet::gettitle($symb);
1.746     raeburn  2274:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2275:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2276: 
                   2277:     if (!&canview($usec)) {
1.712     bisitz   2278:         $request->print(
                   2279:             '<span class="LC_warning">'.
1.713     bisitz   2280:             &mt('Unable to view requested student.').
1.712     bisitz   2281:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2282:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2283:             '</span>');
1.104     albertel 2284: 	return;
                   2285:     }
                   2286: 
1.773   ! raeburn  2287:     my $res_error;
        !          2288:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) =
        !          2289:         &response_type($symb,\$res_error);
        !          2290:     if ($res_error) {
        !          2291:         $request->print(&navmap_errormsg());
        !          2292:         return;
        !          2293:     }
        !          2294: 
1.257     albertel 2295:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2296:     unless ($is_tool) { 
                   2297:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2298:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2299:     }
1.773   ! raeburn  2300:     if (($numessay) && ($calledby eq 'submission') && (!exists($env{'form.compmsg'}))) {
        !          2301:         $env{'form.compmsg'} = 1;
        !          2302:     }
1.257     albertel 2303:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2304:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2305: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2306: 	'/check.gif" height="16" border="0" />';
1.41      ng       2307: 
                   2308:     # header info
                   2309:     if ($counter == 0) {
1.773   ! raeburn  2310:         my @chosenparts = &Apache::loncommon::get_env_multiple('form.vPart');
        !          2311:         if (@chosenparts) {
        !          2312:             $request->print(&showResourceInfo($symb,$partlist,$responseType,'gradesub'));
        !          2313:         } elsif ($divforres) {
        !          2314:             $request->print('<div style="padding:0;clear:both;margin:0;border:0"></div>');
        !          2315:         } else {
        !          2316:             $request->print('<br clear="all" />');
        !          2317:         }
1.41      ng       2318: 	&sub_page_js($request);
1.773   ! raeburn  2319:         &sub_grademessage_js($request) if ($env{'form.compmsg'});
        !          2320: 	&sub_page_kw_js($request) if ($numessay);
1.118     ng       2321: 
1.44      ng       2322: 	# option to display problem, only once else it cause problems 
                   2323:         # with the form later since the problem has a form.
1.257     albertel 2324: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2325: 	    my $mode;
1.257     albertel 2326: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2327: 		$mode='both';
1.257     albertel 2328: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2329: 		$mode='text';
1.257     albertel 2330: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2331: 		$mode='answer';
                   2332: 	    }
1.329     albertel 2333: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2334: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2335: 	}
1.441     www      2336: 
1.41      ng       2337: 	my %keyhash = ();
1.773   ! raeburn  2338: 	if (($env{'form.kwclr'} eq '' && $numessay) || ($env{'form.compmsg'})) {
1.41      ng       2339: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2340: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2341: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.773   ! raeburn  2342: 	}
        !          2343: 	# kwclr is the only variable that is guaranteed not to be blank
        !          2344: 	# if this subroutine has been called once.
        !          2345: 	if ($env{'form.kwclr'} eq '' && $numessay) {
1.257     albertel 2346: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2347: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2348: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2349: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2350: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1.773   ! raeburn  2351: 	}
        !          2352: 	if ($env{'form.compmsg'}) {
        !          2353: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ?
1.605     www      2354: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2355: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2356: 	}
1.773   ! raeburn  2357: 
1.257     albertel 2358: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2359: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2360: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2361: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2362: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2363: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2364: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2365: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2366: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2367: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2368: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2369: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2370: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.773   ! raeburn  2371: 			'<input type="hidden" name="compmsg"    value="'.$env{'form.compmsg'}.'" />'."\n".
1.432     banghart 2372: 			&build_section_inputs().
1.326     albertel 2373: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2374: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2375: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.773   ! raeburn  2376: 	if ($env{'form.compmsg'}) {
        !          2377: 	    $request->print('<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
        !          2378: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
        !          2379: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
        !          2380: 	}
        !          2381: 	if ($numessay) {
1.257     albertel 2382: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2383: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2384: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
1.773   ! raeburn  2385: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n");
1.123     ng       2386: 	}
1.773   ! raeburn  2387: 
1.41      ng       2388: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2389: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2390: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2391: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2392: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2393: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2394: 		'" />'."\n".
                   2395: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2396: 	    $cts++;
                   2397: 	}
                   2398: 	$request->print($prnmsg);
1.32      ng       2399: 
1.773   ! raeburn  2400: 	if ($numessay) {
1.652     raeburn  2401: 
                   2402:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2403:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2404:                           keyw => 'Keyword Options',
1.655     raeburn  2405:                           list => 'List',
1.652     raeburn  2406:                           past => 'Paste Selection to List',
1.661     www      2407:                           high => 'Highlight Attribute',
1.773   ! raeburn  2408:                      );
1.88      www      2409: #
                   2410: # Print out the keyword options line
                   2411: #
1.718     bisitz   2412: 	    $request->print(
                   2413:                 '<div class="LC_columnSection">'
                   2414:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2415:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2416:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2417:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2418:  class="page">'.$lt{'past'}.'</a>',
                   2419:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2420:                     {legend => $lt{'keyw'}})
                   2421:                .'</fieldset></div>'
                   2422:             );
                   2423: 
1.88      www      2424: #
                   2425: # Load the other essays for similarity check
                   2426: #
1.753     raeburn  2427:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2428:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2429:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2430:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2431:                 if ($cdom ne '' && $cnum ne '') {
                   2432:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2433:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2434:                         my $apath = $1.'_'.$id;
                   2435:                         $apath=~s/\W/\_/gs;
                   2436:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2437:                     }
                   2438:                 }
                   2439:             } else {
                   2440: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2441: 	        $apath=&escape($apath);
                   2442: 	        $apath=~s/\W/\_/gs;
                   2443:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2444:             }
1.41      ng       2445:         }
                   2446:     }
1.44      ng       2447: 
1.441     www      2448: # This is where output for one specific student would start
1.592     bisitz   2449:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2450:     $request->print(
                   2451:         "\n\n"
                   2452:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2453:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2454:        ."\n"
                   2455:     );
1.441     www      2456: 
1.592     bisitz   2457:     # Show additional functions if allowed
                   2458:     if ($perm{'vgr'}) {
                   2459:         $request->print(
                   2460:             &Apache::loncommon::track_student_link(
1.708     bisitz   2461:                 'View recent activity',
1.592     bisitz   2462:                 $uname,$udom,'check')
                   2463:            .' '
                   2464:         );
                   2465:     }
                   2466:     if ($perm{'opa'}) {
                   2467:         $request->print(
                   2468:             &Apache::loncommon::pprmlink(
                   2469:                 &mt('Set/Change parameters'),
                   2470:                 $uname,$udom,$symb,'check'));
                   2471:     }
                   2472: 
                   2473:     # Show Problem
1.257     albertel 2474:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2475: 	my $mode;
1.257     albertel 2476: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2477: 	    $mode='both';
1.257     albertel 2478: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2479: 	    $mode='text';
1.257     albertel 2480: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2481: 	    $mode='answer';
                   2482: 	}
1.329     albertel 2483: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2484: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2485:     }
1.144     albertel 2486: 
1.257     albertel 2487:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.41      ng       2488: 
1.44      ng       2489:     # Display student info
1.41      ng       2490:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2491: 
1.745     raeburn  2492:     my $boxtitle = &mt('Submissions');
                   2493:     if ($is_tool) {
                   2494:         $boxtitle = &mt('Transactions')
                   2495:     }
1.590     bisitz   2496:     my $result='<div class="LC_Box">'
1.745     raeburn  2497:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2498:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2499:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.773   ! raeburn  2500:     if (($numresp > $numessay) && !$is_tool) {
1.588     bisitz   2501:         $result.='<p class="LC_info">'
                   2502:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2503:                 ."</p>\n";
1.469     albertel 2504:     }
                   2505: 
1.773   ! raeburn  2506:     # If any part of the problem is an essayresponse, then check for collaborators
1.464     albertel 2507:     my $fullname;
                   2508:     my $col_fullnames = [];
1.773   ! raeburn  2509:     if ($numessay) {
1.464     albertel 2510: 	(my $sub_result,$fullname,$col_fullnames)=
                   2511: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2512: 				 $counter);
                   2513: 	$result.=$sub_result;
1.41      ng       2514:     }
1.44      ng       2515:     $request->print($result."\n");
1.773   ! raeburn  2516: 
1.44      ng       2517:     # print student answer/submission
1.773   ! raeburn  2518:     # Options are (1) Last submission only
        !          2519:     #             (2) Last submission (with detailed information for that submission)
        !          2520:     #             (3) All transactions (by date)
        !          2521:     #             (4) The whole record (with detailed information for all transactions)
        !          2522: 
1.745     raeburn  2523:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.773   ! raeburn  2524: 
1.702     kruse    2525:     my $lastsubonly;
1.468     albertel 2526: 
1.702     kruse    2527:     if ($$timestamp eq '') {
                   2528:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2529:     } elsif ($is_tool) {
                   2530:         $lastsubonly =
                   2531:             '<div class="LC_grade_submissions_body">'
                   2532:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2533:     } else {
                   2534:         $lastsubonly =
                   2535:             '<div class="LC_grade_submissions_body">'
                   2536:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2537: 
                   2538: 	my %seenparts;
                   2539: 	my @part_response_id = &flatten_responseType($responseType);
                   2540: 	foreach my $part (@part_response_id) {
                   2541: 	    my ($partid,$respid) = @{ $part };
                   2542: 	    my $display_part=&get_display_part($partid,$symb);
                   2543: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2544: 		if (exists($seenparts{$partid})) { next; }
                   2545: 		$seenparts{$partid}=1;
                   2546:                 $request->print(
                   2547:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2548:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2549:                                '<a href="javascript:viewSubmitter(\''.
                   2550:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2551:                                '\');" target="_self">'.
                   2552:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2553:                     '<br />');
                   2554: 		next;
1.773   ! raeburn  2555: 	    }
1.702     kruse    2556: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2557: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2558:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2559:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2560:                     ' <span class="LC_internal_info">'.
                   2561:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2562:                     '</span>&nbsp; &nbsp;'.
                   2563: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2564: 		next;
                   2565: 	    }
                   2566: 	    foreach my $submission (@$string) {
                   2567: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2568: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2569: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2570: 		# Similarity check
                   2571:                 my $similar='';
                   2572:                 my ($type,$trial,$rndseed);
                   2573:                 if ($hide eq 'rand') {
                   2574:                     $type = 'randomizetry';
                   2575:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2576:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2577:                 }
                   2578: 	        if ($env{'form.checkPlag'}) {
                   2579:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2580: 		        &most_similar($uname,$udom,$symb,$subval);
                   2581: 		    if ($osim) {
                   2582: 			$osim=int($osim*100.0);
                   2583:                         if ($hide eq 'anon') {
                   2584:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2585:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2586:                         } else {
1.753     raeburn  2587: 			    $similar='<hr />';
                   2588:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2589:                                 $similar .= '<h3><span class="LC_warning">'.
                   2590:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2591:                                                 $osim,
                   2592:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2593:                                             '</span></h3>';
                   2594:                             } else {
                   2595:                                 my %old_course_desc;
                   2596:                                 if ($ocrsid ne '') {
                   2597:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2598:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2599:                                     } else {
                   2600:                                         my $args;
                   2601:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2602:                                             $args = {'one_time' => 1};
                   2603:                                         }
                   2604:                                         %old_course_desc =
                   2605:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2606:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2607:                                     }
                   2608:                                     $similar .=
                   2609:                                         '<h3><span class="LC_warning">'.
                   2610:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2611:                                             $osim,
                   2612:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2613:                                             $old_course_desc{'description'},
                   2614:                                             $old_course_desc{'num'},
                   2615:                                             $old_course_desc{'domain'}).
                   2616:                                         '</span></h3>';
                   2617:                                 } else {
                   2618:                                     $similar .=
                   2619:                                         '<h3><span class="LC_warning">'.
                   2620:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2621:                                             $osim,
                   2622:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2623:                                         '</span></h3>';
                   2624:                                 }
                   2625:                             }
                   2626:                             $similar .= '<blockquote><i>'.
                   2627:                                         &keywords_highlight($oessay).
                   2628:                                         '</i></blockquote><hr />';
1.702     kruse    2629:                         }
                   2630: 	            }
                   2631: 		}
                   2632: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2633:                                      undef,$type,$trial,$rndseed);
1.773   ! raeburn  2634:                 if (($env{'form.lastSub'} eq 'lastonly') ||
        !          2635:                     ($env{'form.lastSub'} eq 'datesub')  ||
        !          2636:                     ($env{'form.lastSub'} =~ /^(last|all)$/)) {
1.702     kruse    2637: 		    my $display_part=&get_display_part($partid,$symb);
                   2638:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2639:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2640:                         ' <span class="LC_internal_info">'.
                   2641:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2642:                         '</span>&nbsp; &nbsp;';
                   2643: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2644:                         
                   2645: 		    if (@$files) {
                   2646:                         if ($hide eq 'anon') {
                   2647:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2648:                         } else {
                   2649:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2650:                                         .'<br /><span class="LC_warning">';
                   2651:                             if(@$files == 1) {
                   2652:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2653:                             } else {
1.702     kruse    2654:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2655:                             }
                   2656:                             $lastsubonly .= '</span>';                         
                   2657:                             foreach my $file (@$files) {
                   2658:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2659:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2660:                             }
                   2661:                         }
1.702     kruse    2662: 			$lastsubonly.='<br />';
                   2663:                     }
                   2664:                     if ($hide eq 'anon') {
                   2665:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2666:                     } else {
1.724     raeburn  2667:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2668:                         if ($draft) {
                   2669:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2670:                         }
                   2671:                         $subval =
1.702     kruse    2672: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2673: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2674:                         if ($responsetype eq 'essay') {
                   2675:                             $subval =~ s{\n}{<br />}g;
                   2676:                         }
                   2677:                         $lastsubonly.=$subval."\n";
1.702     kruse    2678:                     }
                   2679: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2680: 		    $lastsubonly.='</div>';
1.41      ng       2681: 		}
1.702     kruse    2682:             }
1.151     albertel 2683: 	}
1.702     kruse    2684: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2685:     }
                   2686:     $request->print($lastsubonly);
                   2687:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2688:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2689: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.773   ! raeburn  2690:     }
1.702     kruse    2691:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2692:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2693:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2694: 								 $env{'request.course.id'},
1.44      ng       2695: 								 $last,'.submission',
1.726     raeburn  2696: 								 'Apache::grades::keywords_highlight',
                   2697:                                                                  $usec,$identifier));
1.41      ng       2698:     }
1.121     ng       2699:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2700: 	.$udom.'" />'."\n");
1.44      ng       2701:     # return if view submission with no grading option
1.618     www      2702:     if (!&canmodify($usec)) {
1.633     www      2703: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2704: 	return;
1.180     albertel 2705:     } else {
1.468     albertel 2706: 	$request->print('</div>'."\n");
1.41      ng       2707:     }
1.33      ng       2708: 
1.773   ! raeburn  2709:     # grading message center
        !          2710: 
        !          2711:     if ($env{'form.compmsg'}) {
        !          2712:         my $result='<div class="LC_Box">'.
        !          2713:                    '<h3 class="LC_hcell">'.&mt('Send Message').'</h3>'.
        !          2714:                    '<div class="LC_grade_message_center_body">';
        !          2715:         my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
        !          2716:         my $msgfor = $givenn.' '.$lastname;
        !          2717:         if (scalar(@$col_fullnames) > 0) {
        !          2718:             my $lastone = pop(@$col_fullnames);
        !          2719:             $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
        !          2720:         }
        !          2721:         $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
        !          2722:         $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
        !          2723:                  '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n".
        !          2724:                  '&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
        !          2725:                  ',\''.$msgfor.'\');" target="_self">'.
        !          2726:                  &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
        !          2727:                  &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
        !          2728:                  ' <img src="'.$request->dir_config('lonIconsURL').
        !          2729:                  '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
        !          2730:                  '<br />&nbsp;('.
        !          2731:                  &mt('Message will be sent when you click on Save &amp; Next below.').")\n".
        !          2732:                  '</div></div>';
        !          2733:         $request->print($result);
1.118     ng       2734:     }
1.41      ng       2735: 
                   2736:     my %seen = ();
                   2737:     my @partlist;
1.129     ng       2738:     my @gradePartRespid;
1.745     raeburn  2739:     my @part_response_id;
                   2740:     if ($is_tool) {
                   2741:         @part_response_id = ([0,'']);
                   2742:     } else {
                   2743:         @part_response_id = &flatten_responseType($responseType);
                   2744:     }
1.585     bisitz   2745:     $request->print(
1.588     bisitz   2746:         '<div class="LC_Box">'
                   2747:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2748:     );
1.592     bisitz   2749:     $request->print(&gradeBox_start());
1.375     albertel 2750:     foreach my $part_response_id (@part_response_id) {
                   2751:     	my ($partid,$respid) = @{ $part_response_id };
                   2752: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2753: 	next if ($seen{$partid} > 0);
1.41      ng       2754: 	$seen{$partid}++;
1.524     raeburn  2755: 	push(@partlist,$partid);
                   2756: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2757: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2758:     }
1.585     bisitz   2759:     $request->print(&gradeBox_end()); # </div>
                   2760:     $request->print('</div>');
1.468     albertel 2761: 
                   2762:     $request->print('<div class="LC_grade_info_links">');
                   2763:     $request->print('</div>');
                   2764: 
1.45      ng       2765:     $result='<input type="hidden" name="partlist'.$counter.
                   2766: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2767:     $result.='<input type="hidden" name="gradePartRespid'.
                   2768: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2769:     my $ctr = 0;
                   2770:     while ($ctr < scalar(@partlist)) {
                   2771: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2772: 	    $partlist[$ctr].'" />'."\n";
                   2773: 	$ctr++;
                   2774:     }
1.468     albertel 2775:     $request->print($result.''."\n");
1.41      ng       2776: 
1.441     www      2777: # Done with printing info for one student
                   2778: 
1.468     albertel 2779:     $request->print('</div>');#LC_grade_show_user
1.441     www      2780: 
                   2781: 
1.41      ng       2782:     # print end of form
                   2783:     if ($counter == $total) {
1.592     bisitz   2784:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2785: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2786: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2787: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2788: 	my $ntstu ='<select name="NTSTU">'.
                   2789: 	    '<option>1</option><option>2</option>'.
                   2790: 	    '<option>3</option><option>5</option>'.
                   2791: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2792: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2793: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2794:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2795: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2796: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2797: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2798: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2799:         $endform.='<span class="LC_warning">'.
                   2800:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2801:                   '</span>'."\n" ;
1.349     albertel 2802:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2803:             "' name='increment' />";
1.485     albertel 2804: 	$endform.='</td></tr></table></form>';
1.41      ng       2805: 	$request->print($endform);
                   2806:     }
                   2807:     return '';
1.38      ng       2808: }
                   2809: 
1.464     albertel 2810: sub check_collaborators {
                   2811:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2812:     my ($result,@col_fullnames);
                   2813:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2814:     foreach my $part (keys(%$handgrade)) {
                   2815: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2816: 					'.maxcollaborators',
                   2817: 					$symb,$udom,$uname);
                   2818: 	next if ($ncol <= 0);
                   2819: 	$part =~ s/\_/\./g;
                   2820: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2821: 	my (@good_collaborators, @bad_collaborators);
                   2822: 	foreach my $possible_collaborator
1.630     www      2823: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2824: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2825: 	    next if ($possible_collaborator eq '');
1.631     www      2826: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2827: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2828: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2829: 	    # Doing this grep allows 'fuzzy' specification
                   2830: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2831: 			       keys(%$classlist));
                   2832: 	    if (! scalar(@matches)) {
                   2833: 		push(@bad_collaborators, $possible_collaborator);
                   2834: 	    } else {
                   2835: 		push(@good_collaborators, @matches);
                   2836: 	    }
                   2837: 	}
                   2838: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2839: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2840: 	    foreach my $name (@good_collaborators) {
                   2841: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2842: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2843: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2844: 	    }
1.630     www      2845: 	    $result.='</ol><br />'."\n";
1.466     albertel 2846: 	    my ($part)=split(/\./,$part);
1.464     albertel 2847: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2848: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2849: 		"\n";
                   2850: 	}
                   2851: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2852: 	    $result.='<div class="LC_warning">';
1.464     albertel 2853: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2854: 	    $result .= '</div>';
                   2855: 	}         
                   2856: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2857: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2858: 	    $result .= &mt('This student has submitted too many '.
                   2859: 		'collaborators.  Maximum is [_1].',$ncol);
                   2860: 	    $result .= '</div>';
                   2861: 	}
                   2862:     }
                   2863:     return ($result,$fullname,\@col_fullnames);
                   2864: }
                   2865: 
1.44      ng       2866: #--- Retrieve the last submission for all the parts
1.38      ng       2867: sub get_last_submission {
1.745     raeburn  2868:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2869:     my (@string,$timestamp,%lasthidden);
1.119     ng       2870:     if ($$returnhash{'version'}) {
1.46      ng       2871: 	my %lasthash=();
                   2872: 	my ($version);
1.119     ng       2873: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2874: 	    foreach my $key (sort(split(/\:/,
                   2875: 					$$returnhash{$version.':keys'}))) {
                   2876: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2877: 		$timestamp = 
1.545     raeburn  2878: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2879: 	    }
                   2880: 	}
1.640     raeburn  2881:         my (%typeparts,%randombytry);
1.596     raeburn  2882:         my $showsurv = 
                   2883:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2884:         foreach my $key (sort(keys(%lasthash))) {
                   2885:             if ($key =~ /\.type$/) {
                   2886:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2887:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2888:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2889:                     my ($ign,@parts) = split(/\./,$key);
                   2890:                     pop(@parts);
1.641     raeburn  2891:                     my $id = join('.',@parts);
1.640     raeburn  2892:                     if ($lasthash{$key} eq 'randomizetry') {
                   2893:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2894:                     } else {
                   2895:                         unless ($showsurv) {
                   2896:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2897:                         }
1.596     raeburn  2898:                     }
                   2899:                     delete($lasthash{$key});
                   2900:                 }
                   2901:             }
                   2902:         }
                   2903:         my @hidden = keys(%typeparts);
1.640     raeburn  2904:         my @randomize = keys(%randombytry);
1.397     albertel 2905: 	foreach my $key (keys(%lasthash)) {
                   2906: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2907:             my $hide;
                   2908:             if (@hidden) {
                   2909:                 foreach my $id (@hidden) {
                   2910:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2911:                         $hide = 'anon';
1.596     raeburn  2912:                         last;
                   2913:                     }
                   2914:                 }
                   2915:             }
1.640     raeburn  2916:             unless ($hide) {
                   2917:                 if (@randomize) {
1.732     raeburn  2918:                     foreach my $id (@randomize) {
1.640     raeburn  2919:                         if ($key =~ /^\Q$id\E/) {
                   2920:                             $hide = 'rand';
                   2921:                             last;
                   2922:                         }
                   2923:                     }
                   2924:                 }
                   2925:             }
1.397     albertel 2926: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2927: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2928:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2929:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2930:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2931: 	}
                   2932:     }
1.397     albertel 2933:     if (!@string) {
1.745     raeburn  2934:         my $msg;
                   2935:         if ($is_tool) {
1.747     raeburn  2936:             $msg = &mt('No grade passed back.');
1.745     raeburn  2937:         } else {
                   2938:             $msg = &mt('Nothing submitted - no attempts.');
                   2939:         }
1.397     albertel 2940: 	$string[0] =
1.745     raeburn  2941: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2942:     }
                   2943:     return (\@string,\$timestamp);
1.38      ng       2944: }
1.35      ng       2945: 
1.44      ng       2946: #--- High light keywords, with style choosen by user.
1.38      ng       2947: sub keywords_highlight {
1.44      ng       2948:     my $string    = shift;
1.257     albertel 2949:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2950:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2951:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2952:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2953:     foreach my $keyword (@keylist) {
                   2954: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2955:     }
                   2956:     return $string;
1.38      ng       2957: }
1.36      ng       2958: 
1.671     raeburn  2959: # For Tasks provide a mechanism to display previous version for one specific student
                   2960: 
                   2961: sub show_previous_task_version {
                   2962:     my ($request,$symb) = @_;
                   2963:     if ($symb eq '') {
1.717     bisitz   2964:         $request->print(
                   2965:             '<span class="LC_error">'.
                   2966:             &mt('Unable to handle ambiguous references.').
                   2967:             '</span>');
1.671     raeburn  2968:         return '';
                   2969:     }
                   2970:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2971:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2972:     if (!&canview($usec)) {
1.712     bisitz   2973:         $request->print(
                   2974:             '<span class="LC_warning">'.
1.713     bisitz   2975:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2976:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2977:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2978:             '</span>');
1.671     raeburn  2979:         return;
                   2980:     }
                   2981:     my $mode = 'both';
                   2982:     my $isTask = ($symb =~/\.task$/);
                   2983:     if ($isTask) {
                   2984:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2985:             if ($env{'form.fullname'} eq '') {
                   2986:                 $env{'form.fullname'} =
                   2987:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2988:             }
                   2989:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2990:             $request->print("\n\n".
                   2991:                             '<div class="LC_grade_show_user">'.
                   2992:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2993:                             '</h2>'."\n");
                   2994:             &Apache::lonxml::clear_problem_counter();
                   2995:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2996:                             {'previousversion' => $env{'form.previousversion'} }));
                   2997:             $request->print("\n</div>");
                   2998:         }
                   2999:     }
                   3000:     return;
                   3001: }
                   3002: 
                   3003: sub choose_task_version_form {
                   3004:     my ($symb,$uname,$udom,$nomenu) = @_;
                   3005:     my $isTask = ($symb =~/\.task$/);
                   3006:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   3007:     if ($isTask) {
                   3008:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3009:                                               $udom,$uname);
                   3010:         if (($record{'resource.0.version'} eq '') ||
                   3011:             ($record{'resource.0.version'} < 2)) {
                   3012:             return ($record{'resource.0.version'},
                   3013:                     $record{'resource.0.version'},$result,$js);
                   3014:         } else {
                   3015:             $current = $record{'resource.0.version'};
                   3016:         }
                   3017:         if ($env{'form.previousversion'}) {
                   3018:             $displayed = $env{'form.previousversion'};
                   3019:             $rowtitle = &mt('Choose another version:')
                   3020:         } else {
                   3021:             $displayed = $current;
                   3022:             $rowtitle = &mt('Show earlier version:');
                   3023:         }
                   3024:         $result = '<div class="LC_left_float">';
                   3025:         my $list;
                   3026:         my $numversions = 0;
                   3027:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   3028:             if ($i == $current) {
                   3029:                 if (!$env{'form.previousversion'} || $nomenu) {
                   3030:                     next;
                   3031:                 } else {
                   3032:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   3033:                     $numversions ++;
                   3034:                 }
                   3035:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   3036:                 unless ($i == $env{'form.previousversion'}) {
                   3037:                     $numversions ++;
                   3038:                 }
                   3039:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   3040:             }
                   3041:         }
                   3042:         if ($numversions) {
                   3043:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   3044:             $result .=
                   3045:                 '<form name="getprev" method="post" action=""'.
                   3046:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   3047:                 &Apache::loncommon::start_data_table().
                   3048:                 &Apache::loncommon::start_data_table_row().
                   3049:                 '<th align="left">'.$rowtitle.'</th>'.
                   3050:                 '<td><select name="version">'.
                   3051:                 '<option>'.&mt('Select').'</option>'.
                   3052:                 $list.
                   3053:                 '</select></td>'.
                   3054:                 &Apache::loncommon::end_data_table_row();
                   3055:             unless ($nomenu) {
                   3056:                 $result .= &Apache::loncommon::start_data_table_row().
                   3057:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   3058:                 '<td><span class="LC_nobreak">'.
                   3059:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   3060:                 &mt('Yes').'</label>'.
                   3061:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   3062:                 '</span></td>'.
                   3063:                 &Apache::loncommon::end_data_table_row();
                   3064:             }
                   3065:             $result .=
                   3066:                 &Apache::loncommon::start_data_table_row().
                   3067:                 '<th align="left">&nbsp;</th>'.
                   3068:                 '<td>'.
                   3069:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   3070:                 '</td>'.
                   3071:                 &Apache::loncommon::end_data_table_row().
                   3072:                 &Apache::loncommon::end_data_table().
                   3073:                 '</form>';
                   3074:             $js = &previous_display_javascript($nomenu,$current);
                   3075:         } elsif ($displayed && $nomenu) {
                   3076:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   3077:         } else {
                   3078:             $result .= &mt('No previous versions to show for this student');
                   3079:         }
                   3080:         $result .= '</div>';
                   3081:     }
                   3082:     return ($current,$displayed,$result,$js);
                   3083: }
                   3084: 
                   3085: sub previous_display_javascript {
                   3086:     my ($nomenu,$current) = @_;
                   3087:     my $js = <<"JSONE";
                   3088: <script type="text/javascript">
                   3089: // <![CDATA[
                   3090: function previousVersion(uname,udom,symb) {
                   3091:     var current = '$current';
                   3092:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   3093:     var prevstr = new RegExp("^\\\\d+\$");
                   3094:     if (!prevstr.test(version)) {
                   3095:         return false;
                   3096:     }
                   3097:     var url = '';
                   3098:     if (version == current) {
                   3099:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   3100:     } else {
                   3101:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   3102:     }
                   3103: JSONE
                   3104:     if ($nomenu) {
                   3105:         $js .= <<"JSTWO";
                   3106:     document.location.href = url;
                   3107: JSTWO
                   3108:     } else {
                   3109:         $js .= <<"JSTHREE";
                   3110:     var newwin = 0;
                   3111:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   3112:         if (document.getprev.prevwin[i].checked == true) {
                   3113:             newwin = document.getprev.prevwin[i].value;
                   3114:         }
                   3115:     }
                   3116:     if (newwin == 1) {
                   3117:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   3118:         url = url+'&inhibitmenu=yes';
                   3119:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   3120:             previousWin = window.open(url,'',options,1);
                   3121:         } else {
                   3122:             previousWin.location.href = url;
                   3123:         }
                   3124:         previousWin.focus();
                   3125:         return false;
                   3126:     } else {
                   3127:         document.location.href = url;
                   3128:         return false;
                   3129:     }
                   3130: JSTHREE
                   3131:     }
                   3132:     $js .= <<"ENDJS";
                   3133:     return false;
                   3134: }
                   3135: // ]]>
                   3136: </script>
                   3137: ENDJS
                   3138: 
                   3139: }
                   3140: 
1.44      ng       3141: #--- Called from submission routine
1.38      ng       3142: sub processHandGrade {
1.608     www      3143:     my ($request,$symb) = @_;
1.324     albertel 3144:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 3145:     my $button = $env{'form.gradeOpt'};
                   3146:     my $ngrade = $env{'form.NCT'};
                   3147:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 3148:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3149:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3150: 
1.44      ng       3151:     if ($button eq 'Save & Next') {
                   3152: 	my $ctr = 0;
                   3153: 	while ($ctr < $ngrade) {
1.257     albertel 3154: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3155: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3156:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3157: 	    if ($errorflag eq 'no_score') {
                   3158: 		$ctr++;
                   3159: 		next;
                   3160: 	    }
1.104     albertel 3161: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3162: 		$request->print(
                   3163:                     '<span class="LC_error">'
                   3164:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3165:                    .'</span>');
1.104     albertel 3166: 		$ctr++;
                   3167: 		next;
                   3168: 	    }
1.726     raeburn  3169:             if ($numhidden) {
                   3170:                 $request->print(
                   3171:                     '<span class="LC_info">'
                   3172:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3173:                    .'</span><br />');
                   3174:             }
1.257     albertel 3175: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3176: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3177: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3178:             my ($feedurl,$showsymb) =
                   3179: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3180: 	    my $messagetail;
1.62      albertel 3181: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3182: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3183: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3184: 		$subject.=' ['.$restitle.']';
1.44      ng       3185: 		my (@msgnum) = split(/,/,$includemsg);
                   3186: 		foreach (@msgnum) {
1.257     albertel 3187: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3188: 		}
1.80      ng       3189: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3190: 		if ($env{'form.withgrades'.$ctr}) {
                   3191: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3192: 		    $messagetail = " for <a href=\"".
1.605     www      3193: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3194: 		}
                   3195: 		$msgstatus = 
                   3196:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3197: 						     $message.$messagetail,
1.418     albertel 3198:                                                      undef,$feedurl,undef,
1.386     raeburn  3199:                                                      undef,undef,$showsymb,
                   3200:                                                      $restitle);
1.574     bisitz   3201: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3202: 				$msgstatus.'<br />');
1.44      ng       3203: 	    }
1.257     albertel 3204: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3205: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3206: 		foreach my $collabstr (@collabstrs) {
                   3207: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3208: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3209: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3210: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3211: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3212: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3213: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3214: 			    next;
1.418     albertel 3215: 			} elsif ($message ne '') {
                   3216: 			    my ($baseurl,$showsymb) = 
                   3217: 				&get_feedurl_and_symb($symb,$collaborator,
                   3218: 						      $udom);
                   3219: 			    if ($env{'form.withgrades'.$ctr}) {
                   3220: 				$messagetail = " for <a href=\"".
1.605     www      3221:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3222: 			    }
1.418     albertel 3223: 			    $msgstatus = 
                   3224: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3225: 			}
1.44      ng       3226: 		    }
                   3227: 		}
                   3228: 	    }
                   3229: 	    $ctr++;
                   3230: 	}
                   3231:     }
                   3232: 
1.773   ! raeburn  3233:     my $res_error;
        !          3234:     my ($partlist,$handgrade,$responseType,$numresp,$numessay) = &response_type($symb,\$res_error);
        !          3235:     if ($res_error) {
        !          3236:         $request->print(&navmap_errormsg());
        !          3237:         return;
        !          3238:     }
        !          3239: 
        !          3240:     my %keyhash = ();
        !          3241:     if ($numessay) {
1.119     ng       3242: 	# Keywords sorted in alphabatical order
1.257     albertel 3243: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   3244: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3245: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3246: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3247: 	$env{'form.keywords'} = join(' ',@keywords);
                   3248: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3249: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3250: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3251: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3252: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.773   ! raeburn  3253:     }
1.119     ng       3254: 
1.773   ! raeburn  3255:     if ($env{'form.compmsg'}) {
1.119     ng       3256: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3257: 	# New messages are saved in env for the next student.
1.119     ng       3258: 	# All messages are saved in nohist_handgrade.db
                   3259: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3260: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3261: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3262: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3263: 		$idx++;
                   3264: 	    }
                   3265: 	    $ctr++;
1.41      ng       3266: 	}
1.119     ng       3267: 	$ctr = 0;
                   3268: 	while ($ctr < $ngrade) {
1.257     albertel 3269: 	    if ($env{'form.newmsg'.$ctr} ne '') {
1.773   ! raeburn  3270: 	        $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
        !          3271: 	        $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
        !          3272: 	        $idx++;
1.119     ng       3273: 	    }
                   3274: 	    $ctr++;
1.41      ng       3275: 	}
1.257     albertel 3276: 	$env{'form.savemsgN'} = --$idx;
                   3277: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.41      ng       3278:     }
1.773   ! raeburn  3279:     if (($numessay) || ($env{'form.compmsg'})) {
        !          3280:         my $putresult = &Apache::lonnet::put
        !          3281:             ('nohist_handgrade',\%keyhash,$cdom,$cnum);
        !          3282:     }
        !          3283: 
1.44      ng       3284:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3285:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3286:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3287: 	my ($ctr,$total) = (0,0);
                   3288: 	while ($ctr < $ngrade) {
1.257     albertel 3289: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3290: 	    $ctr++;
                   3291: 	}
1.257     albertel 3292: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3293: 	$ctr = 0;
                   3294: 	while ($ctr < $total) {
1.257     albertel 3295: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3296: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3297: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3298: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3299: 	    $ctr++;
                   3300: 	}
                   3301: 	return '';
                   3302:     }
1.36      ng       3303: 
1.44      ng       3304:     # Get the next/previous one or group of students
1.257     albertel 3305:     my $firststu = $env{'form.unamedom0'};
                   3306:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3307:     my $ctr = 2;
1.41      ng       3308:     while ($laststu eq '') {
1.257     albertel 3309: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3310: 	$ctr++;
                   3311: 	$laststu = $firststu if ($ctr > $ngrade);
                   3312:     }
1.44      ng       3313: 
1.41      ng       3314:     my (@parsedlist,@nextlist);
                   3315:     my ($nextflg) = 0;
1.524     raeburn  3316:     foreach my $item (sort 
1.294     albertel 3317: 	     {
                   3318: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3319: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3320: 		 }
                   3321: 		 return $a cmp $b;
                   3322: 	     } (keys(%$fullname))) {
1.41      ng       3323: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3324: 	    push(@parsedlist,$item);
1.41      ng       3325: 	}
1.524     raeburn  3326: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3327: 	if ($button eq 'Previous') {
1.524     raeburn  3328: 	    last if ($item eq $firststu);
                   3329: 	    push(@parsedlist,$item);
1.41      ng       3330: 	}
                   3331:     }
                   3332:     $ctr = 0;
                   3333:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
                   3334:     foreach my $student (@parsedlist) {
1.257     albertel 3335: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3336: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3337: 	
                   3338: 	if ($submitonly eq 'queued') {
                   3339: 	    my %queue_status = 
                   3340: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3341: 							$udom,$uname);
                   3342: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3343: 	}
                   3344: 
1.156     albertel 3345: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3346: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3347: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3348: 	    my $submitted = 0;
1.248     albertel 3349: 	    my $ungraded = 0;
                   3350: 	    my $incorrect = 0;
1.524     raeburn  3351: 	    foreach my $item (keys(%status)) {
                   3352: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3353: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3354: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3355: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3356: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3357: 		    $submitted = 0;
                   3358: 		}
1.41      ng       3359: 	    }
1.156     albertel 3360: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3361: 				     $submitonly eq 'incorrect' ||
                   3362: 				     $submitonly eq 'graded'));
1.248     albertel 3363: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3364: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3365: 	}
1.524     raeburn  3366: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3367: 	last if ($ctr == $ntstu);
1.41      ng       3368: 	$ctr++;
                   3369:     }
1.36      ng       3370: 
1.41      ng       3371:     $ctr = 0;
                   3372:     my $total = scalar(@nextlist)-1;
1.39      ng       3373: 
1.524     raeburn  3374:     foreach (sort(@nextlist)) {
1.41      ng       3375: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3376: 	$env{'form.student'}  = $uname;
                   3377: 	$env{'form.userdom'}  = $udom;
                   3378: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3379: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3380: 	$ctr++;
                   3381:     }
                   3382:     if ($total < 0) {
1.653     raeburn  3383: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3384: 	$request->print($the_end);
                   3385:     }
                   3386:     return '';
1.38      ng       3387: }
1.36      ng       3388: 
1.44      ng       3389: #---- Save the score and award for each student, if changed
1.38      ng       3390: sub saveHandGrade {
1.324     albertel 3391:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3392:     my @version_parts;
1.104     albertel 3393:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3394: 					   $env{'request.course.id'});
1.104     albertel 3395:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3396:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3397:     my @parts_graded;
1.77      ng       3398:     my %newrecord  = ();
1.726     raeburn  3399:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3400:     my %aggregate = ();
                   3401:     my $aggregateflag = 0;
1.726     raeburn  3402:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3403:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3404:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3405:         $totchg += $numchgs;
                   3406:     }
1.301     albertel 3407:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3408:     foreach my $new_part (@parts) {
1.337     banghart 3409: 	#collaborator ($submi may vary for different parts
1.259     banghart 3410: 	if ($submitter && $new_part ne $part) { next; }
                   3411: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3412: 	if ($dropMenu eq 'excused') {
1.259     banghart 3413: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3414: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3415: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3416: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3417: 		}
1.364     banghart 3418: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3419: 	    }
1.125     ng       3420: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3421: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3422: 	    foreach my $key (keys(%record)) {
1.259     banghart 3423: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3424: 	    }
1.259     banghart 3425: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3426: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3427:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3428: 
                   3429:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3430: 					       [$new_part]);
                   3431:             my $aggtries =$totaltries;
1.269     raeburn  3432:             if ($last_resets{$new_part}) {
1.270     albertel 3433:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3434: 					   $new_part);
1.269     raeburn  3435:             }
1.270     albertel 3436: 
                   3437:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3438:             if ($aggtries > 0) {
1.327     albertel 3439:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3440:                 $aggregateflag = 1;
                   3441:             }
1.125     ng       3442: 	} elsif ($dropMenu eq '') {
1.259     banghart 3443: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3444: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3445: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3446: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3447: 		next;
                   3448: 	    }
1.259     banghart 3449: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3450: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3451: 	    my $partial= $pts/$wgt;
1.259     banghart 3452: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3453: 		#do not update score for part if not changed.
1.346     banghart 3454:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3455: 		next;
1.251     banghart 3456: 	    } else {
1.524     raeburn  3457: 	        push(@parts_graded,$new_part);
1.153     albertel 3458: 	    }
1.259     banghart 3459: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3460: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3461: 	    }
1.259     banghart 3462: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3463: 	    if ($partial == 0) {
1.153     albertel 3464: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3465: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3466: 		}
1.41      ng       3467: 	    } else {
1.153     albertel 3468: 		if ($record{$reckey} ne 'correct_by_override') {
                   3469: 		    $newrecord{$reckey} = 'correct_by_override';
                   3470: 		}
                   3471: 	    }	    
                   3472: 	    if ($submitter && 
1.259     banghart 3473: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3474: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3475: 	    }
1.259     banghart 3476: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3477: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3478: 	}
1.259     banghart 3479: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3480: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3481: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3482: 	        $dropMenu eq 'reset status')
                   3483: 	   {
1.524     raeburn  3484: 	    push(@version_parts,$new_part);
1.259     banghart 3485: 	}
1.41      ng       3486:     }
1.301     albertel 3487:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3488:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3489: 
1.344     albertel 3490:     if (%newrecord) {
                   3491:         if (@version_parts) {
1.364     banghart 3492:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3493:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3494: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3495: 	    foreach my $new_part (@version_parts) {
                   3496: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3497: 				$new_part,\%newrecord);
                   3498: 	    }
1.259     banghart 3499:         }
1.44      ng       3500: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3501: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3502: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3503: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3504:     }
1.269     raeburn  3505:     if ($aggregateflag) {
                   3506:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3507: 			      $cdom,$cnum);
1.269     raeburn  3508:     }
1.726     raeburn  3509:     return ('',$pts,$wgt,$totchg);
                   3510: }
                   3511: 
                   3512: sub makehidden {
1.728     raeburn  3513:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3514:     return unless (ref($record) eq 'HASH');
                   3515:     my %modified;
                   3516:     my $numchanged = 0;
                   3517:     if (exists($record->{$version.':keys'})) {
                   3518:         my $partsregexp = $parts;
                   3519:         $partsregexp =~ s/,/|/g;
                   3520:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3521:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3522:                  my $item = $1;
                   3523:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3524:                      $modified{$key} = $record->{$version.':'.$key};
                   3525:                  }
                   3526:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3527:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3528:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3529:                 $modified{$key} = $record->{$version.':'.$key};
                   3530:             }
                   3531:         }
                   3532:         if (keys(%modified)) {
                   3533:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3534:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3535:                 $numchanged ++;
                   3536:             }
                   3537:         }
                   3538:     }
                   3539:     return $numchanged;
1.36      ng       3540: }
1.322     albertel 3541: 
1.380     albertel 3542: sub check_and_remove_from_queue {
                   3543:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3544:     my @ungraded_parts;
                   3545:     foreach my $part (@{$parts}) {
                   3546: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3547: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3548: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3549: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3550: 		) {
                   3551: 	    push(@ungraded_parts, $part);
                   3552: 	}
                   3553:     }
                   3554:     if ( !@ungraded_parts ) {
                   3555: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3556: 					       $cnum,$domain,$stuname);
                   3557:     }
                   3558: }
                   3559: 
1.337     banghart 3560: sub handback_files {
                   3561:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3562:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3563:     my $res_error;
                   3564:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3565:     if ($res_error) {
                   3566:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3567:         return;
                   3568:     }
1.654     raeburn  3569:     my @handedback;
                   3570:     my $file_msg;
1.375     albertel 3571:     my @part_response_id = &flatten_responseType($responseType);
                   3572:     foreach my $part_response_id (@part_response_id) {
                   3573:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3574: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3575:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3576:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3577:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3578:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3579:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3580:                     my ($directory,$answer_file) = 
1.654     raeburn  3581:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3582:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3583: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3584: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3585:                     my $getpropath = 1;
1.773   ! raeburn  3586:                     my ($dir_list,$listerror) =
1.662     raeburn  3587:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3588:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3589: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3590:                     # fix filename
1.355     banghart 3591:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3592:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3593:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3594:             	                                $save_file_name);
1.337     banghart 3595:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3596:                         $request->print('<br /><span class="LC_error">'.
                   3597:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3598:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3599:                                         '</span>');
1.356     banghart 3600:                     } else {
1.360     banghart 3601:                         # mark the file as read only
1.654     raeburn  3602:                         push(@handedback,$save_file_name);
1.367     albertel 3603: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3604: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3605: 			}
                   3606:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3607: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3608:                     }
1.686     bisitz   3609:                     $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 3610:                 }
                   3611:             }
                   3612:         }
1.654     raeburn  3613:     }
                   3614:     if (@handedback > 0) {
                   3615:         $request->print('<br />');
                   3616:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3617:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3618:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3619:         my ($subject,$message);
                   3620:         if (scalar(@handedback) == 1) {
                   3621:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3622:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3623:         } else {
                   3624:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3625:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3626:         }
                   3627:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3628:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3629:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3630:         my ($feedurl,$showsymb) =
                   3631:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3632:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3633:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3634:         my $msgstatus =
                   3635:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3636:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3637:                  $restitle);
                   3638:         if ($msgstatus) {
                   3639:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3640:         }
                   3641:     }
1.338     banghart 3642:     return;
1.337     banghart 3643: }
                   3644: 
1.418     albertel 3645: sub get_feedurl_and_symb {
                   3646:     my ($symb,$uname,$udom) = @_;
                   3647:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3648:     $url = &Apache::lonnet::clutter($url);
                   3649:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3650: 					$symb,$udom,$uname);
                   3651:     if ($encrypturl =~ /^yes$/i) {
                   3652: 	&Apache::lonenc::encrypted(\$url,1);
                   3653: 	&Apache::lonenc::encrypted(\$symb,1);
                   3654:     }
                   3655:     return ($url,$symb);
                   3656: }
                   3657: 
1.313     banghart 3658: sub get_submitted_files {
                   3659:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3660:     my @files;
                   3661:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3662:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3663:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3664:     	    push(@files,$file_url.$file);
                   3665:         }
                   3666:     }
                   3667:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3668:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3669:     }
                   3670:     return (\@files);
                   3671: }
1.322     albertel 3672: 
1.269     raeburn  3673: # ----------- Provides number of tries since last reset.
                   3674: sub get_num_tries {
                   3675:     my ($record,$last_reset,$part) = @_;
                   3676:     my $timestamp = '';
                   3677:     my $num_tries = 0;
                   3678:     if ($$record{'version'}) {
                   3679:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3680:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3681:                 $timestamp = $$record{$version.':timestamp'};
                   3682:                 if ($timestamp > $last_reset) {
                   3683:                     $num_tries ++;
                   3684:                 } else {
                   3685:                     last;
                   3686:                 }
                   3687:             }
                   3688:         }
                   3689:     }
                   3690:     return $num_tries;
                   3691: }
                   3692: 
                   3693: # ----------- Determine decrements required in aggregate totals 
                   3694: sub decrement_aggs {
                   3695:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3696:     my %decrement = (
                   3697:                         attempts => 0,
                   3698:                         users => 0,
                   3699:                         correct => 0
                   3700:                     );
                   3701:     $decrement{'attempts'} = $aggtries;
                   3702:     if ($solvedstatus =~ /^correct/) {
                   3703:         $decrement{'correct'} = 1;
                   3704:     }
                   3705:     if ($aggtries == $totaltries) {
                   3706:         $decrement{'users'} = 1;
                   3707:     }
1.524     raeburn  3708:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3709:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3710:     }
                   3711:     return;
                   3712: }
                   3713: 
                   3714: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3715: sub get_last_resets {
1.270     albertel 3716:     my ($symb,$courseid,$partids) =@_;
                   3717:     my %last_resets;
1.269     raeburn  3718:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3719:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3720:     my @keys;
                   3721:     foreach my $part (@{$partids}) {
                   3722: 	push(@keys,"$symb\0$part\0resettime");
                   3723:     }
                   3724:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3725: 				     $cdom,$cname);
                   3726:     foreach my $part (@{$partids}) {
                   3727: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3728:     }
1.270     albertel 3729:     return %last_resets;
1.269     raeburn  3730: }
                   3731: 
1.251     banghart 3732: # ----------- Handles creating versions for portfolio files as answers
                   3733: sub version_portfiles {
1.343     banghart 3734:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3735:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3736:     my @returned_keys;
1.255     banghart 3737:     my $parts = join('|', @$parts_graded);
1.277     albertel 3738:     foreach my $key (keys(%$record)) {
1.259     banghart 3739:         my $new_portfiles;
1.263     banghart 3740:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3741:             my @versioned_portfiles;
1.367     albertel 3742:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3743:             if (@portfiles) {
                   3744:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3745:                                                       \@versioned_portfiles);
1.252     banghart 3746:             }
1.343     banghart 3747:             $$record{$key} = join(',',@versioned_portfiles);
                   3748:             push(@returned_keys,$key);
1.251     banghart 3749:         }
                   3750:     } 
1.343     banghart 3751:     return (@returned_keys);   
1.305     banghart 3752: }
                   3753: 
1.44      ng       3754: #--------------------------------------------------------------------------------------
                   3755: #
                   3756: #-------------------------- Next few routines handles grading by section or whole class
                   3757: #
                   3758: #--- Javascript to handle grading by section or whole class
1.42      ng       3759: sub viewgrades_js {
                   3760:     my ($request) = shift;
                   3761: 
1.539     riegler  3762:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3763:     &js_escape(\$alertmsg);
1.597     wenzelju 3764:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3765:    function writePoint(partid,weight,point) {
1.125     ng       3766: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3767: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3768: 	if (point == "textval") {
1.125     ng       3769: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3770: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3771: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3772: 		var resetbox = false;
                   3773: 		for (var i=0; i<radioButton.length; i++) {
                   3774: 		    if (radioButton[i].checked) {
                   3775: 			textbox.value = i;
                   3776: 			resetbox = true;
                   3777: 		    }
                   3778: 		}
                   3779: 		if (!resetbox) {
                   3780: 		    textbox.value = "";
                   3781: 		}
                   3782: 		return;
                   3783: 	    }
1.109     matthew  3784: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3785: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3786: 				   ") greater than the weight for the part. Accept?");
                   3787: 		if (resp == false) {
                   3788: 		    textbox.value = "";
                   3789: 		    return;
                   3790: 		}
                   3791: 	    }
1.42      ng       3792: 	    for (var i=0; i<radioButton.length; i++) {
                   3793: 		radioButton[i].checked=false;
1.109     matthew  3794: 		if (parseFloat(point) == i) {
1.42      ng       3795: 		    radioButton[i].checked=true;
                   3796: 		}
                   3797: 	    }
1.41      ng       3798: 
1.42      ng       3799: 	} else {
1.125     ng       3800: 	    textbox.value = parseFloat(point);
1.42      ng       3801: 	}
1.41      ng       3802: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3803: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3804: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3805: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3806: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3807: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3808: 	    if (saveval != "correct") {
                   3809: 		scorename.value = point;
1.43      ng       3810: 		if (selname[0].selected != true) {
                   3811: 		    selname[0].selected = true;
                   3812: 		}
1.42      ng       3813: 	    }
                   3814: 	}
1.125     ng       3815: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3816:     }
                   3817: 
                   3818:     function writeRadText(partid,weight) {
1.125     ng       3819: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3820: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3821:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3822: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3823: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3824: 	    for (var i=0; i<radioButton.length; i++) {
                   3825: 		radioButton[i].checked=false;
                   3826: 
                   3827: 	    }
                   3828: 	    textbox.value = "";
                   3829: 
                   3830: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3831: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3832: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3833: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3834: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3835: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3836: 		if ((saveval != "correct") || override) {
1.42      ng       3837: 		    scorename.value = "";
1.125     ng       3838: 		    if (selval[1].selected) {
                   3839: 			selname[1].selected = true;
                   3840: 		    } else {
                   3841: 			selname[2].selected = true;
                   3842: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3843: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3844: 		    }
1.42      ng       3845: 		}
                   3846: 	    }
1.43      ng       3847: 	} else {
                   3848: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3849: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3850: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3851: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3852: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3853: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3854: 		if ((saveval != "correct") || override) {
1.125     ng       3855: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3856: 		    selname[0].selected = true;
                   3857: 		}
                   3858: 	    }
                   3859: 	}	    
1.42      ng       3860:     }
                   3861: 
                   3862:     function changeSelect(partid,user) {
1.125     ng       3863: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3864: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3865: 	var point  = textbox.value;
1.125     ng       3866: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3867: 
1.109     matthew  3868: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3869: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3870: 	    textbox.value = "";
                   3871: 	    return;
                   3872: 	}
1.109     matthew  3873: 	if (parseFloat(point) > parseFloat(weight)) {
                   3874: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3875: 			       ") greater than the weight of the part. Accept?");
                   3876: 	    if (resp == false) {
                   3877: 		textbox.value = "";
                   3878: 		return;
                   3879: 	    }
                   3880: 	}
1.42      ng       3881: 	selval[0].selected = true;
                   3882:     }
                   3883: 
                   3884:     function changeOneScore(partid,user) {
1.125     ng       3885: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3886: 	if (selval[1].selected || selval[2].selected) {
                   3887: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3888: 	    if (selval[2].selected) {
                   3889: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3890: 	    }
1.269     raeburn  3891:         }
1.42      ng       3892:     }
                   3893: 
                   3894:     function resetEntry(numpart) {
                   3895: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3896: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3897: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3898: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3899: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3900: 	    for (var i=0; i<radioButton.length; i++) {
                   3901: 		radioButton[i].checked=false;
                   3902: 
                   3903: 	    }
                   3904: 	    textbox.value = "";
                   3905: 	    selval[0].selected = true;
                   3906: 
                   3907: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3908: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3909: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3910: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3911: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3912: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3913: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3914: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3915: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3916: 		if (saveselval == "excused") {
1.43      ng       3917: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3918: 		} else {
1.43      ng       3919: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3920: 		}
                   3921: 	    }
1.41      ng       3922: 	}
1.42      ng       3923:     }
                   3924: 
1.41      ng       3925: VIEWJAVASCRIPT
1.42      ng       3926: }
                   3927: 
1.44      ng       3928: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3929: sub viewgrades {
1.608     www      3930:     my ($request,$symb) = @_;
1.745     raeburn  3931:     my ($is_tool,$toolsymb);
                   3932:     if ($symb =~ /ext\.tool$/) {
                   3933:         $is_tool = 1;
                   3934:         $toolsymb = $symb;
                   3935:     }
1.42      ng       3936:     &viewgrades_js($request);
1.41      ng       3937: 
1.168     albertel 3938:     #need to make sure we have the correct data for later EXT calls, 
                   3939:     #thus invalidate the cache
                   3940:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3941:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3942:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3943:     &Apache::lonnet::clear_EXT_cache_status();
                   3944: 
1.398     albertel 3945:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3946: 
                   3947:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3948:     $result.=&jscriptNform($symb);
1.41      ng       3949: 
1.44      ng       3950:     #beginning of class grading form
1.442     banghart 3951:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3952:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3953: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3954: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3955: 	&build_section_inputs().
1.442     banghart 3956: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3957: 
1.738     raeburn  3958:     #retrieve selected groups
                   3959:     my (@groups,$group_display);
                   3960:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3961:     if (grep(/^all$/,@groups)) {
                   3962:         @groups = ('all');
                   3963:     } elsif (grep(/^none$/,@groups)) {
                   3964:         @groups = ('none');
                   3965:     } elsif (@groups > 0) {
                   3966:         $group_display = join(', ',@groups);
                   3967:     }
                   3968: 
                   3969:     my ($common_header,$specific_header,@sections,$section_display);
                   3970:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3971:     if (grep(/^all$/,@sections)) {
                   3972:         @sections = ('all');
                   3973:         if ($group_display) {
                   3974:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3975:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3976:         } elsif (grep(/^none$/,@groups)) {
                   3977:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3978:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3979:         } else {
                   3980: 	    $common_header = &mt('Assign Common Grade to Class');
                   3981:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3982:         }
                   3983:     } elsif (grep(/^none$/,@sections)) {
                   3984:         @sections = ('none');
                   3985:         if ($group_display) {
                   3986:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3987:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3988:         } elsif (grep(/^none$/,@groups)) {
                   3989:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3990:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3991:         } else {
                   3992:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3993: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3994:         }
                   3995:     } else {
                   3996:         $section_display = join (", ",@sections);
                   3997:         if ($group_display) {
                   3998:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3999:                                  $section_display,$group_display);
                   4000:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   4001:                                    $section_display,$group_display);
                   4002:         } elsif (grep(/^none$/,@groups)) {
                   4003:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   4004:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   4005:         } else {
                   4006:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   4007: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   4008:         }
                   4009:     }
                   4010:     my %submit_types = &substatus_options();
                   4011:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   4012: 
                   4013:     if ($env{'form.submitonly'} eq 'all') {
                   4014:         $result.= '<h3>'.$common_header.'</h3>';
                   4015:     } else {
1.745     raeburn  4016:         my $text;
                   4017:         if ($is_tool) {
                   4018:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4019:         } else {
                   4020:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4021:         }
                   4022:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 4023:     }
1.738     raeburn  4024:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       4025:     #radio buttons/text box for assigning points for a section or class.
                   4026:     #handles different parts of a problem
1.582     raeburn  4027:     my $res_error;
                   4028:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   4029:     if ($res_error) {
                   4030:         return &navmap_errormsg();
                   4031:     }
1.42      ng       4032:     my %weight = ();
                   4033:     my $ctsparts = 0;
1.45      ng       4034:     my %seen = ();
1.745     raeburn  4035:     my @part_response_id;
                   4036:     if ($is_tool) {
                   4037:         @part_response_id = ([0,'']);
                   4038:     } else {
                   4039:         @part_response_id = &flatten_responseType($responseType);
                   4040:     }
1.375     albertel 4041:     foreach my $part_response_id (@part_response_id) {
                   4042:     	my ($partid,$respid) = @{ $part_response_id };
                   4043: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       4044: 	next if $seen{$partid};
                   4045: 	$seen{$partid}++;
1.42      ng       4046: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   4047: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   4048: 
1.324     albertel 4049: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 4050: 	my $radio.='<table border="0"><tr>';  
1.41      ng       4051: 	my $ctr = 0;
1.42      ng       4052: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 4053: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 4054: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 4055: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       4056: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   4057: 	    $ctr++;
                   4058: 	}
1.485     albertel 4059: 	$radio.='</tr></table>';
                   4060: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   4061: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 4062: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  4063: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   4064:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   4065:             '<select name="SELVAL_'.$partid.'" '.
                   4066:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   4067:                 $weight{$partid}.')"> '.
1.401     albertel 4068: 	    '<option selected="selected"> </option>'.
1.485     albertel 4069: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   4070: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   4071: 	    '</select></td>'.
                   4072:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   4073: 	$line.='<input type="hidden" name="partid_'.
                   4074: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   4075: 	$line.='<input type="hidden" name="weight_'.
                   4076: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   4077: 
                   4078: 	$result.=
                   4079: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   4080: 	    '<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 4081: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       4082: 	$ctsparts++;
1.41      ng       4083:     }
1.474     albertel 4084:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 4085: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 4086:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   4087: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       4088: 
1.44      ng       4089:     #table listing all the students in a section/class
                   4090:     #header of table
1.738     raeburn  4091:     if ($env{'form.submitonly'} eq 'all') {
                   4092:         $result.= '<h3>'.$specific_header.'</h3>';
                   4093:     } else {
1.745     raeburn  4094:         my $text;
                   4095:         if ($is_tool) {
                   4096:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   4097:         } else {
                   4098:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   4099:         }
                   4100:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  4101:     }
                   4102:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  4103: 	      &Apache::loncommon::start_data_table_header_row().
                   4104: 	      '<th>'.&mt('No.').'</th>'.
                   4105: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  4106:     my $partserror;
                   4107:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4108:     if ($partserror) {
                   4109:         return &navmap_errormsg();
                   4110:     }
1.324     albertel 4111:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  4112:     my @partids = ();
1.41      ng       4113:     foreach my $part (@parts) {
1.745     raeburn  4114: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  4115:         my $narrowtext = &mt('Tries');
                   4116: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  4117: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 4118: 	my ($partid) = &split_part_type($part);
1.524     raeburn  4119:         push(@partids,$partid);
1.628     www      4120: #
                   4121: # FIXME: Looks like $display looks at English text
                   4122: #
1.324     albertel 4123: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       4124: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 4125: 	    $result.='<th>'.
1.697     bisitz   4126: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   4127: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       4128: 	    next;
1.485     albertel 4129: 	    
1.207     albertel 4130: 	} else {
1.485     albertel 4131: 	    if ($display =~ /Problem Status/) {
                   4132: 		my $grade_status_mt = &mt('Grade Status');
                   4133: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   4134: 	    }
                   4135: 	    my $part_mt = &mt('Part:');
                   4136: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       4137: 	}
1.485     albertel 4138: 
1.474     albertel 4139: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       4140:     }
1.474     albertel 4141:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       4142: 
1.270     albertel 4143:     my %last_resets = 
                   4144: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  4145: 
1.41      ng       4146:     #get info for each student
1.44      ng       4147:     #list all the students - with points and grade status
1.738     raeburn  4148:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       4149:     my $ctr = 0;
1.294     albertel 4150:     foreach (sort 
                   4151: 	     {
                   4152: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4153: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4154: 		 }
                   4155: 		 return $a cmp $b;
                   4156: 	     } (keys(%$fullname))) {
1.324     albertel 4157: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4158: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4159:     }
1.474     albertel 4160:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4161:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4162:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4163: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4164:     if ($ctr == 0) {
1.442     banghart 4165:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4166:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4167:                 '<span class="LC_warning">';
                   4168:         if ($env{'form.submitonly'} eq 'all') {
                   4169:             if (grep(/^all$/,@sections)) {
                   4170:                 if (grep(/^all$/,@groups)) {
                   4171:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4172:                                    $stu_status);
                   4173:                 } elsif (grep(/^none$/,@groups)) {
                   4174:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4175:                                    $stu_status); 
                   4176:                 } else {
                   4177:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4178:                                    $group_display,$stu_status);
                   4179:                 }
                   4180:             } elsif (grep(/^none$/,@sections)) {
                   4181:                 if (grep(/^all$/,@groups)) {
                   4182:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4183:                                    $stu_status);
                   4184:                 } elsif (grep(/^none$/,@groups)) {
                   4185:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4186:                                    $stu_status);
                   4187:                 } else {
                   4188:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4189:                                    $group_display,$stu_status);
                   4190:                 }
                   4191:             } else {
                   4192:                 if (grep(/^all$/,@groups)) {
                   4193:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4194:                                    $section_display,$stu_status);
                   4195:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4196:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4197:                                    $section_display,$stu_status);
                   4198:                 } else {
                   4199:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4200:                                    $section_display,$group_display,$stu_status);
                   4201:                 }
                   4202:             }
                   4203:         } else {
                   4204:             if (grep(/^all$/,@sections)) {
                   4205:                 if (grep(/^all$/,@groups)) {
                   4206:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4207:                                    $stu_status,$submission_status);
                   4208:                 } elsif (grep(/^none$/,@groups)) {
                   4209:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4210:                                    $stu_status,$submission_status);
                   4211:                 } else {
                   4212:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4213:                                    $group_display,$stu_status,$submission_status);
                   4214:                 }
                   4215:             } elsif (grep(/^none$/,@sections)) {
                   4216:                 if (grep(/^all$/,@groups)) {
                   4217:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4218:                                    $stu_status,$submission_status);
                   4219:                 } elsif (grep(/^none$/,@groups)) {
                   4220:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4221:                                    $stu_status,$submission_status);
                   4222:                 } else {
                   4223:                     $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.',
                   4224:                                    $group_display,$stu_status,$submission_status);
                   4225:                 }
                   4226:             } else {
                   4227:                 if (grep(/^all$/,@groups)) {
                   4228: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4229: 	                           $section_display,$stu_status,$submission_status);
                   4230:                 } elsif (grep(/^none$/,@groups)) {
                   4231:                     $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.',
                   4232:                                    $section_display,$stu_status,$submission_status);
                   4233:                 } else {
                   4234:                     $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.',
                   4235:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4236:                 }
                   4237:             }
                   4238:         }
                   4239: 	$result .= '</span><br />';
1.96      albertel 4240:     }
1.41      ng       4241:     return $result;
                   4242: }
                   4243: 
1.738     raeburn  4244: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4245: sub viewstudentgrade {
1.745     raeburn  4246:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4247:     my ($uname,$udom) = split(/:/,$student);
                   4248:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4249:     my $submitonly = $env{'form.submitonly'};
                   4250:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4251:         my %partstatus = ();
                   4252:         if (ref($parts) eq 'ARRAY') {
                   4253:             foreach my $apart (@{$parts}) {
                   4254:                 my ($part,$type) = &split_part_type($apart);
                   4255:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4256:                 $status = 'nothing' if ($status eq '');
                   4257:                 $partstatus{$part}      = $status;
                   4258:                 my $subkey = "resource.$part.submitted_by";
                   4259:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4260:             }
                   4261:             my $submitted = 0;
                   4262:             my $graded = 0;
                   4263:             my $incorrect = 0;
                   4264:             foreach my $key (keys(%partstatus)) {
                   4265:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4266:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4267:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4268: 
                   4269:                 my $partid = (split(/\./,$key))[1];
                   4270:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4271:                     $submitted = 0;
                   4272:                 }
                   4273:             }
                   4274:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4275:                                        $submitonly eq 'incorrect' ||
                   4276:                                        $submitonly eq 'graded'));
                   4277:             return if (!$graded && ($submitonly eq 'graded'));
                   4278:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4279:         }
                   4280:     }
                   4281:     if ($submitonly eq 'queued') {
                   4282:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4283:         my %queue_status =
                   4284:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4285:                                                     $udom,$uname);
                   4286:         return if (!defined($queue_status{'gradingqueue'}));
                   4287:     }
                   4288:     $$ctr++;
                   4289:     my %aggregates = ();
1.474     albertel 4290:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4291: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4292: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4293: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4294: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4295: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4296:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4297:     foreach my $apart (@$parts) {
                   4298: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4299: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4300:         $result.='<td align="center">';
1.269     raeburn  4301:         my ($aggtries,$totaltries);
                   4302:         unless (exists($aggregates{$part})) {
1.270     albertel 4303: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4304: 	    $aggtries = $totaltries;
1.269     raeburn  4305:             if ($$last_resets{$part}) {  
1.270     albertel 4306:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4307: 					   $part);
                   4308:             }
1.269     raeburn  4309:             $result.='<input type="hidden" name="'.
                   4310:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4311:             $result.='<input type="hidden" name="'.
                   4312:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4313:             $aggregates{$part} = 1;
                   4314:         }
1.41      ng       4315: 	if ($type eq 'awarded') {
1.320     albertel 4316: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4317: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4318: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4319: 	    $result.='<input type="text" name="'.
1.89      albertel 4320: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4321:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4322: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4323: 	} elsif ($type eq 'solved') {
                   4324: 	    my ($status,$foo)=split(/_/,$score,2);
                   4325: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4326: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4327: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4328: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4329: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4330:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4331: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4332: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4333: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4334: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4335: 	} else {
                   4336: 	    $result.='<input type="hidden" name="'.
                   4337: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4338: 		    "\n";
1.233     albertel 4339: 	    $result.='<input type="text" name="'.
1.122     ng       4340: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4341: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4342: 	}
                   4343:     }
1.474     albertel 4344:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4345:     return $result;
1.38      ng       4346: }
                   4347: 
1.44      ng       4348: #--- change scores for all the students in a section/class
                   4349: #    record does not get update if unchanged
1.38      ng       4350: sub editgrades {
1.608     www      4351:     my ($request,$symb) = @_;
1.745     raeburn  4352:     my $toolsymb;
                   4353:     if ($symb =~ /ext\.tool$/) {
                   4354:         $toolsymb = $symb;
                   4355:     }
1.41      ng       4356: 
1.433     banghart 4357:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4358:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4359:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4360: 
1.477     albertel 4361:     my $result= &Apache::loncommon::start_data_table().
                   4362: 	&Apache::loncommon::start_data_table_header_row().
                   4363: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4364: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4365:     my %scoreptr = (
                   4366: 		    'correct'  =>'correct_by_override',
                   4367: 		    'incorrect'=>'incorrect_by_override',
                   4368: 		    'excused'  =>'excused',
                   4369: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4370:                     'credited' =>'credit_attempted',
1.43      ng       4371: 		    'nothing'  => '',
                   4372: 		    );
1.257     albertel 4373:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4374: 
1.44      ng       4375:     my (@partid);
                   4376:     my %weight = ();
1.54      albertel 4377:     my %columns = ();
1.44      ng       4378:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4379: 
1.582     raeburn  4380:     my $partserror;
                   4381:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4382:     if ($partserror) {
                   4383:         return &navmap_errormsg();
                   4384:     }
1.54      albertel 4385:     my $header;
1.257     albertel 4386:     while ($ctr < $env{'form.totalparts'}) {
                   4387: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4388: 	push(@partid,$partid);
1.257     albertel 4389: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4390: 	$ctr++;
1.54      albertel 4391:     }
1.324     albertel 4392:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4393:     my $totcolspan = 0;
1.54      albertel 4394:     foreach my $partid (@partid) {
1.478     albertel 4395: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4396: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4397: 	$columns{$partid}=2;
                   4398: 	foreach my $stores (@parts) {
                   4399: 	    my ($part,$type) = &split_part_type($stores);
                   4400: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4401: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4402: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4403: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4404:             my $narrowtext = &mt('Tries');
                   4405: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4406: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4407: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4408: 	    $columns{$partid}+=2;
                   4409: 	}
1.748     raeburn  4410:         $totcolspan += $columns{$partid};
1.54      albertel 4411:     }
                   4412:     foreach my $partid (@partid) {
1.324     albertel 4413: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4414: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4415: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4416: 	    '</th>';
1.54      albertel 4417: 
1.44      ng       4418:     }
1.477     albertel 4419:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4420: 	&Apache::loncommon::start_data_table_header_row().
                   4421: 	$header.
                   4422: 	&Apache::loncommon::end_data_table_header_row();
                   4423:     my @noupdate;
1.126     ng       4424:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4425:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4426: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4427: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4428: 	my %newrecord;
                   4429: 	my $updateflag = 0;
1.108     albertel 4430: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4431: 	my $canmodify = &canmodify($usec);
                   4432: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4433: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4434: 	if (!$canmodify) {
1.477     albertel 4435: 	    push(@noupdate,
1.748     raeburn  4436: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4437: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4438: 	    next;
                   4439: 	}
1.269     raeburn  4440:         my %aggregate = ();
                   4441:         my $aggregateflag = 0;
1.281     albertel 4442: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4443: 	foreach (@partid) {
1.257     albertel 4444: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4445: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4446: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4447: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4448: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4449: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4450: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4451: 	    my $score;
                   4452: 	    if ($partial eq '') {
1.257     albertel 4453: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4454: 	    } elsif ($partial > 0) {
                   4455: 		$score = 'correct_by_override';
                   4456: 	    } elsif ($partial == 0) {
                   4457: 		$score = 'incorrect_by_override';
                   4458: 	    }
1.257     albertel 4459: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4460: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4461: 
1.292     albertel 4462: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4463: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4464: 	    if ($dropMenu eq 'reset status' &&
                   4465: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4466: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4467: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4468: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4469: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4470: 		$updateflag = 1;
1.269     raeburn  4471:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4472:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4473:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4474:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4475:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4476:                     $aggregateflag = 1;
                   4477:                 }
1.139     albertel 4478: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4479: 		$updateflag = 1;
                   4480: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4481: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4482: 		$rec_update++;
1.125     ng       4483: 	    }
                   4484: 
1.93      albertel 4485: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4486: 		'<td align="center">'.$awarded.
                   4487: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4488: 
1.54      albertel 4489: 
                   4490: 	    my $partid=$_;
                   4491: 	    foreach my $stores (@parts) {
                   4492: 		my ($part,$type) = &split_part_type($stores);
                   4493: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4494: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4495: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4496: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4497: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4498: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4499: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4500: 		    $updateflag=1;
                   4501: 		}
1.93      albertel 4502: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4503: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4504: 	    }
1.44      ng       4505: 	}
1.477     albertel 4506: 	$line.="\n";
1.301     albertel 4507: 
                   4508: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4509: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4510: 
1.44      ng       4511: 	if ($updateflag) {
                   4512: 	    $count++;
1.257     albertel 4513: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4514: 				    $udom,$uname);
1.301     albertel 4515: 
                   4516: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4517: 					      $cnum,$udom,$uname)) {
                   4518: 		# need to figure out if should be in queue.
                   4519: 		my %record =  
                   4520: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4521: 					     $udom,$uname);
                   4522: 		my $all_graded = 1;
                   4523: 		my $none_graded = 1;
                   4524: 		foreach my $part (@parts) {
                   4525: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4526: 			$all_graded = 0;
                   4527: 		    } else {
                   4528: 			$none_graded = 0;
                   4529: 		    }
                   4530: 		}
                   4531: 
                   4532: 		if ($all_graded || $none_graded) {
                   4533: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4534: 							   $symb,$cdom,$cnum,
                   4535: 							   $udom,$uname);
                   4536: 		}
                   4537: 	    }
                   4538: 
1.477     albertel 4539: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4540: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4541: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4542: 	    $updateCtr++;
1.93      albertel 4543: 	} else {
1.477     albertel 4544: 	    push(@noupdate,
                   4545: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4546: 	    $noupdateCtr++;
1.44      ng       4547: 	}
1.269     raeburn  4548:         if ($aggregateflag) {
                   4549:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4550: 				  $cdom,$cnum);
1.269     raeburn  4551:         }
1.93      albertel 4552:     }
1.477     albertel 4553:     if (@noupdate) {
1.748     raeburn  4554:         my $numcols=$totcolspan+2;
1.477     albertel 4555: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4556: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4557: 	    &mt('No Changes Occurred For the Students Below').
                   4558: 	    '</td>'.
1.477     albertel 4559: 	    &Apache::loncommon::end_data_table_row();
                   4560: 	foreach my $line (@noupdate) {
                   4561: 	    $result.=
                   4562: 		&Apache::loncommon::start_data_table_row().
                   4563: 		$line.
                   4564: 		&Apache::loncommon::end_data_table_row();
                   4565: 	}
1.44      ng       4566:     }
1.614     www      4567:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4568:     my $msg = '<p><b>'.
                   4569: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4570: 	    $rec_update,$count).'</b><br />'.
                   4571: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4572: 	'</b></p>';
1.44      ng       4573:     return $title.$msg.$result;
1.5       albertel 4574: }
1.54      albertel 4575: 
                   4576: sub split_part_type {
                   4577:     my ($partstr) = @_;
                   4578:     my ($temp,@allparts)=split(/_/,$partstr);
                   4579:     my $type=pop(@allparts);
1.439     albertel 4580:     my $part=join('_',@allparts);
1.54      albertel 4581:     return ($part,$type);
                   4582: }
                   4583: 
1.44      ng       4584: #------------- end of section for handling grading by section/class ---------
                   4585: #
                   4586: #----------------------------------------------------------------------------
                   4587: 
1.5       albertel 4588: 
1.44      ng       4589: #----------------------------------------------------------------------------
                   4590: #
                   4591: #-------------------------- Next few routines handles grading by csv upload
                   4592: #
                   4593: #--- Javascript to handle csv upload
1.27      albertel 4594: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4595:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4596:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4597:   &js_escape(\$error1);
                   4598:   &js_escape(\$error2);
1.27      albertel 4599:   return(<<ENDPICK);
                   4600:   function verify(vf) {
                   4601:     var foundsomething=0;
                   4602:     var founduname=0;
1.243     albertel 4603:     var foundID=0;
1.743     raeburn  4604:     var foundclicker=0;
1.27      albertel 4605:     for (i=0;i<=vf.nfields.value;i++) {
                   4606:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4607:       if (i==0 && tw!=0) { foundID=1; }
                   4608:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4609:       if (i==2 && tw!=0) { foundclicker=1; }
                   4610:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4611:     }
1.743     raeburn  4612:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4613: 	alert('$error1');
                   4614: 	return;
1.27      albertel 4615:     }
                   4616:     if (foundsomething==0) {
1.246     albertel 4617: 	alert('$error2');
                   4618: 	return;
1.27      albertel 4619:     }
                   4620:     vf.submit();
                   4621:   }
                   4622:   function flip(vf,tf) {
                   4623:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4624:     var i;
                   4625:     for (i=0;i<=vf.nfields.value;i++) {
                   4626:       //can not pick the same destination field for both name and domain
                   4627:       if (((i ==0)||(i ==1)) && 
                   4628:           ((tf==0)||(tf==1)) && 
                   4629:           (i!=tf) &&
                   4630:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4631:         eval('vf.f'+i+'.selectedIndex=0;')
                   4632:       }
                   4633:     }
                   4634:   }
                   4635: ENDPICK
                   4636: }
                   4637: 
                   4638: sub csvupload_javascript_forward_associate {
1.743     raeburn  4639:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4640:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4641:   &js_escape(\$error1);
                   4642:   &js_escape(\$error2);
1.27      albertel 4643:   return(<<ENDPICK);
                   4644:   function verify(vf) {
                   4645:     var foundsomething=0;
                   4646:     var founduname=0;
1.243     albertel 4647:     var foundID=0;
1.743     raeburn  4648:     var foundclicker=0;
1.27      albertel 4649:     for (i=0;i<=vf.nfields.value;i++) {
                   4650:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4651:       if (tw==1) { foundID=1; }
                   4652:       if (tw==2) { founduname=1; }
1.745     raeburn  4653:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4654:       if (tw>4) { foundsomething=1; }
1.27      albertel 4655:     }
1.743     raeburn  4656:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4657: 	alert('$error1');
                   4658: 	return;
1.27      albertel 4659:     }
                   4660:     if (foundsomething==0) {
1.246     albertel 4661: 	alert('$error2');
                   4662: 	return;
1.27      albertel 4663:     }
                   4664:     vf.submit();
                   4665:   }
                   4666:   function flip(vf,tf) {
                   4667:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4668:     var i;
                   4669:     //can not pick the same destination field twice
                   4670:     for (i=0;i<=vf.nfields.value;i++) {
                   4671:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4672:         eval('vf.f'+i+'.selectedIndex=0;')
                   4673:       }
                   4674:     }
                   4675:   }
                   4676: ENDPICK
                   4677: }
                   4678: 
1.26      albertel 4679: sub csvuploadmap_header {
1.324     albertel 4680:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4681:     my $javascript;
1.257     albertel 4682:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4683: 	$javascript=&csvupload_javascript_reverse_associate();
                   4684:     } else {
                   4685: 	$javascript=&csvupload_javascript_forward_associate();
                   4686:     }
1.45      ng       4687: 
1.418     albertel 4688:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4689:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4690:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4691:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4692:     my $reverse=&mt("Reverse Association");
1.41      ng       4693:     $request->print(<<ENDPICK);
1.632     www      4694: <br />
                   4695: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4696: <input type="hidden" name="associate"  value="" />
                   4697: <input type="hidden" name="phase"      value="three" />
                   4698: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4699: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4700: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4701: <input type="hidden" name="upfile_associate" 
1.257     albertel 4702:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4703: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4704: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4705: <hr />
                   4706: ENDPICK
1.597     wenzelju 4707:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4708:     return '';
1.26      albertel 4709: 
                   4710: }
                   4711: 
                   4712: sub csvupload_fields {
1.582     raeburn  4713:     my ($symb,$errorref) = @_;
1.745     raeburn  4714:     my $toolsymb;
                   4715:     if ($symb =~ /ext\.tool$/) {
                   4716:         $toolsymb = $symb;
                   4717:     }
1.582     raeburn  4718:     my (@parts) = &getpartlist($symb,$errorref);
                   4719:     if (ref($errorref)) {
                   4720:         if ($$errorref) {
                   4721:             return;
                   4722:         }
                   4723:     }
                   4724: 
1.556     weissno  4725:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4726: 		['username','Student Username'],
1.743     raeburn  4727: 		['clicker','Clicker ID'],
1.243     albertel 4728: 		['domain','Student Domain']);
1.324     albertel 4729:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4730:     foreach my $part (sort(@parts)) {
                   4731: 	my @datum;
1.745     raeburn  4732: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4733: 	my $name=$part;
1.745     raeburn  4734: 	if (!$display) { $display = $name; }
1.41      ng       4735: 	@datum=($name,$display);
1.244     albertel 4736: 	if ($name=~/^stores_(.*)_awarded/) {
                   4737: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4738: 	}
1.41      ng       4739: 	push(@fields,\@datum);
                   4740:     }
                   4741:     return (@fields);
1.26      albertel 4742: }
                   4743: 
                   4744: sub csvuploadmap_footer {
1.41      ng       4745:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4746:     my $buttontext = &mt('Assign Grades');
1.41      ng       4747:     $request->print(<<ENDPICK);
1.26      albertel 4748: </table>
                   4749: <input type="hidden" name="nfields" value="$i" />
                   4750: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4751: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4752: </form>
                   4753: ENDPICK
                   4754: }
                   4755: 
1.283     albertel 4756: sub checkforfile_js {
1.638     www      4757:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4758:     &js_escape(\$alertmsg);
1.597     wenzelju 4759:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4760:     function checkUpload(formname) {
                   4761: 	if (formname.upfile.value == "") {
1.539     riegler  4762: 	    alert("$alertmsg");
1.86      ng       4763: 	    return false;
                   4764: 	}
                   4765: 	formname.submit();
                   4766:     }
                   4767: CSVFORMJS
1.283     albertel 4768:     return $result;
                   4769: }
                   4770: 
                   4771: sub upcsvScores_form {
1.608     www      4772:     my ($request,$symb) = @_;
1.283     albertel 4773:     if (!$symb) {return '';}
                   4774:     my $result=&checkforfile_js();
1.632     www      4775:     $result.=&Apache::loncommon::start_data_table().
                   4776:              &Apache::loncommon::start_data_table_header_row().
                   4777:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4778:              &Apache::loncommon::end_data_table_header_row().
                   4779:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4780:     my $upload=&mt("Upload Scores");
1.86      ng       4781:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4782:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4783:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4784:     $result.=<<ENDUPFORM;
1.106     albertel 4785: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4786: <input type="hidden" name="symb" value="$symb" />
                   4787: <input type="hidden" name="command" value="csvuploadmap" />
                   4788: $upfile_select
1.589     bisitz   4789: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4790: </form>
                   4791: ENDUPFORM
1.370     www      4792:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4793:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4794:              '</td>'.
                   4795:             &Apache::loncommon::end_data_table_row().
                   4796:             &Apache::loncommon::end_data_table();
1.86      ng       4797:     return $result;
                   4798: }
                   4799: 
                   4800: 
1.26      albertel 4801: sub csvuploadmap {
1.768     raeburn  4802:     my ($request,$symb) = @_;
1.41      ng       4803:     if (!$symb) {return '';}
1.72      ng       4804: 
1.41      ng       4805:     my $datatoken;
1.257     albertel 4806:     if (!$env{'form.datatoken'}) {
1.41      ng       4807: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4808:     } else {
1.742     raeburn  4809: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4810:         if ($datatoken ne '') {
                   4811: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4812:         }
1.26      albertel 4813:     }
1.41      ng       4814:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4815:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4816:     my ($i,$keyfields);
                   4817:     if (@records) {
1.582     raeburn  4818:         my $fieldserror;
                   4819: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4820:         if ($fieldserror) {
                   4821:             $request->print(&navmap_errormsg());
                   4822:             return;
                   4823:         }
1.257     albertel 4824: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4825: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4826: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4827: 							  \@fields);
                   4828: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4829: 	    chop($keyfields);
                   4830: 	} else {
                   4831: 	    unshift(@fields,['none','']);
                   4832: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4833: 							    \@fields);
1.311     banghart 4834:             foreach my $rec (@records) {
                   4835:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4836:                 if (%temp) {
                   4837:                     $keyfields=join(',',sort(keys(%temp)));
                   4838:                     last;
                   4839:                 }
                   4840:             }
1.41      ng       4841: 	}
                   4842:     }
                   4843:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4844: 
1.41      ng       4845:     return '';
1.27      albertel 4846: }
                   4847: 
1.246     albertel 4848: sub csvuploadoptions {
1.608     www      4849:     my ($request,$symb)= @_;
1.632     www      4850:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4851:     $request->print(<<ENDPICK);
                   4852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4853: <input type="hidden" name="command"    value="csvuploadassign" />
                   4854: <p>
                   4855: <label>
                   4856:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4857:    $overwrite
1.246     albertel 4858: </label>
                   4859: </p>
                   4860: ENDPICK
                   4861:     my %fields=&get_fields();
                   4862:     if (!defined($fields{'domain'})) {
1.257     albertel 4863: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4864: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4865:     }
1.257     albertel 4866:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4867: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4868: 	my $cleankey=$1;
                   4869: 	if ($cleankey eq 'command') { next; }
                   4870: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4871: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4872:     }
                   4873:     # FIXME do a check for any duplicated user ids...
                   4874:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4875:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4876: <hr /></form>'."\n");
1.246     albertel 4877:     return '';
                   4878: }
                   4879: 
                   4880: sub get_fields {
                   4881:     my %fields;
1.257     albertel 4882:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4883:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4884: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4885: 	    if ($env{'form.f'.$i} ne 'none') {
                   4886: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4887: 	    }
                   4888: 	} else {
1.257     albertel 4889: 	    if ($env{'form.f'.$i} ne 'none') {
                   4890: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4891: 	    }
                   4892: 	}
1.27      albertel 4893:     }
1.246     albertel 4894:     return %fields;
                   4895: }
                   4896: 
                   4897: sub csvuploadassign {
1.766     raeburn  4898:     my ($request,$symb) = @_;
1.246     albertel 4899:     if (!$symb) {return '';}
1.345     bowersj2 4900:     my $error_msg = '';
1.742     raeburn  4901:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4902:     if ($datatoken ne '') { 
                   4903:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4904:     }
1.246     albertel 4905:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4906:     my %fields=&get_fields();
1.257     albertel 4907:     my $courseid=$env{'request.course.id'};
1.97      albertel 4908:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4909:     my @notallowed;
1.41      ng       4910:     my @skipped;
1.657     raeburn  4911:     my @warnings;
1.41      ng       4912:     my $countdone=0;
                   4913:     foreach my $grade (@gradedata) {
                   4914: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4915: 	my $domain;
                   4916: 	if ($entries{$fields{'domain'}}) {
                   4917: 	    $domain=$entries{$fields{'domain'}};
                   4918: 	} else {
1.257     albertel 4919: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4920: 	}
1.243     albertel 4921: 	$domain=~s/\s//g;
1.41      ng       4922: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4923: 	$username=~s/\s//g;
1.243     albertel 4924: 	if (!$username) {
                   4925: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4926: 	    $id=~s/\s//g;
1.737     raeburn  4927:             if ($id ne '') {
                   4928: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4929: 	        $username=$ids{$id};
                   4930:             } else {
                   4931:                 if ($entries{$fields{'clicker'}}) {
                   4932:                     my $clicker = $entries{$fields{'clicker'}};
                   4933:                     $clicker=~s/\s//g;
                   4934:                     if ($clicker ne '') {
                   4935:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4936:                         if ($clickers{$clicker} ne '') {  
                   4937:                             my $match = 0;
                   4938:                             my @inclass;
                   4939:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4940:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4941:                                     $username = $poss;
                   4942:                                     push(@inclass,$poss);
                   4943:                                     $match ++;
                   4944:                                     
                   4945:                                 }
                   4946:                             }
                   4947:                             if ($match > 1) {
                   4948:                                 undef($username); 
                   4949:                                 $request->print('<p class="LC_warning">'.
                   4950:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4951:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4952:                             }
                   4953:                         }
                   4954:                     }
                   4955:                 }
                   4956:             }
1.243     albertel 4957: 	}
1.41      ng       4958: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4959: 	    my $id=$entries{$fields{'ID'}};
                   4960: 	    $id=~s/\s//g;
1.737     raeburn  4961:             my $clicker = $entries{$fields{'clicker'}};
                   4962:             $clicker=~s/\s//g;
                   4963:             if ($clicker) {
                   4964:                 push(@skipped,"$clicker:$domain");
                   4965: 	    } elsif ($id) {
1.247     albertel 4966: 		push(@skipped,"$id:$domain");
                   4967: 	    } else {
                   4968: 		push(@skipped,"$username:$domain");
                   4969: 	    }
1.41      ng       4970: 	    next;
                   4971: 	}
1.108     albertel 4972: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4973: 	if (!&canmodify($usec)) {
                   4974: 	    push(@notallowed,"$username:$domain");
                   4975: 	    next;
                   4976: 	}
1.244     albertel 4977: 	my %points;
1.41      ng       4978: 	my %grades;
                   4979: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4980: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4981: 		$dest eq 'domain') { next; }
                   4982: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4983: 	    if ($dest=~/stores_(.*)_points/) {
                   4984: 		my $part=$1;
                   4985: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4986: 					      $symb,$domain,$username);
1.345     bowersj2 4987:                 if ($wgt) {
                   4988:                     $entries{$fields{$dest}}=~s/\s//g;
                   4989:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4990:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4991:                                           : 'correct_by_override';
1.638     www      4992:                     if ($pcr>1) {
1.657     raeburn  4993:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4994:                     }
1.345     bowersj2 4995:                     $grades{"resource.$part.awarded"}=$pcr;
                   4996:                     $grades{"resource.$part.solved"}=$award;
                   4997:                     $points{$part}=1;
                   4998:                 } else {
                   4999:                     $error_msg = "<br />" .
                   5000:                         &mt("Some point values were assigned"
                   5001:                             ." for problems with a weight "
                   5002:                             ."of zero. These values were "
                   5003:                             ."ignored.");
                   5004:                 }
1.244     albertel 5005: 	    } else {
                   5006: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   5007: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   5008: 		my $store_key=$dest;
                   5009: 		$store_key=~s/^stores/resource/;
                   5010: 		$store_key=~s/_/\./g;
                   5011: 		$grades{$store_key}=$entries{$fields{$dest}};
                   5012: 	    }
1.41      ng       5013: 	}
1.766     raeburn  5014: 	if (! %grades) {
1.508     www      5015:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   5016:         } else {
                   5017: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   5018: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 5019: 					   $env{'request.course.id'},
                   5020: 					   $domain,$username);
1.508     www      5021: 	   if ($result eq 'ok') {
1.627     www      5022: # Successfully stored
1.508     www      5023: 	      $request->print('.');
1.627     www      5024: # Remove from grading queue
                   5025:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   5026:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5027:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   5028:                                              $domain,$username);
                   5029:               $countdone++;
                   5030:            } else {
1.508     www      5031: 	      $request->print("<p><span class=\"LC_error\">".
                   5032:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   5033:                                   "$username:$domain",$result)."</span></p>");
                   5034: 	   }
                   5035: 	   $request->rflush();
                   5036:         }
1.41      ng       5037:     }
1.570     www      5038:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  5039:     if (@warnings) {
                   5040:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   5041:         $request->print(join(', ',@warnings));
                   5042:     }
1.41      ng       5043:     if (@skipped) {
1.571     www      5044: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   5045:         $request->print(join(', ',@skipped));
1.106     albertel 5046:     }
                   5047:     if (@notallowed) {
1.571     www      5048: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   5049: 	$request->print(join(', ',@notallowed));
1.41      ng       5050:     }
1.106     albertel 5051:     $request->print("<br />\n");
1.345     bowersj2 5052:     return $error_msg;
1.26      albertel 5053: }
1.44      ng       5054: #------------- end of section for handling csv file upload ---------
                   5055: #
                   5056: #-------------------------------------------------------------------
                   5057: #
1.122     ng       5058: #-------------- Next few routines handle grading by page/sequence
1.72      ng       5059: #
                   5060: #--- Select a page/sequence and a student to grade
1.68      ng       5061: sub pickStudentPage {
1.608     www      5062:     my ($request,$symb) = @_;
1.68      ng       5063: 
1.539     riegler  5064:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  5065:     &js_escape(\$alertmsg);
1.597     wenzelju 5066:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       5067: 
                   5068: function checkPickOne(formname) {
1.76      ng       5069:     if (radioSelection(formname.student) == null) {
1.539     riegler  5070: 	alert("$alertmsg");
1.68      ng       5071: 	return;
                   5072:     }
1.125     ng       5073:     ptr = pullDownSelection(formname.selectpage);
                   5074:     formname.page.value = formname["page"+ptr].value;
                   5075:     formname.title.value = formname["title"+ptr].value;
1.68      ng       5076:     formname.submit();
                   5077: }
                   5078: 
                   5079: LISTJAVASCRIPT
1.118     ng       5080:     &commonJSfunctions($request);
1.608     www      5081: 
1.257     albertel 5082:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5083:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5084:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  5085:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       5086: 
1.398     albertel 5087:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 5088: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       5089: 
1.80      ng       5090:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  5091:     my $map_error;
                   5092:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5093:     if ($map_error) {
                   5094:         $request->print(&navmap_errormsg());
                   5095:         return; 
                   5096:     }
1.137     albertel 5097:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   5098: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   5099: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   5100: 
                   5101:     # Collection of hidden fields
1.70      ng       5102:     my $ctr=0;
1.68      ng       5103:     foreach (@$titles) {
1.700     bisitz   5104:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5105:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   5106:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   5107:         $ctr++;
1.68      ng       5108:     }
1.700     bisitz   5109:     $result.='<input type="hidden" name="page" />'."\n".
                   5110:         '<input type="hidden" name="title" />'."\n";
                   5111: 
                   5112:     $result.=&build_section_inputs();
                   5113:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   5114:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   5115: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   5116: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 5117: 
1.700     bisitz   5118:     # Show grading options
                   5119:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   5120:     my $select = '<select name="selectpage">'."\n";
1.70      ng       5121:     $ctr=0;
                   5122:     foreach (@$titles) {
                   5123: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   5124: 	$select.='<option value="'.$ctr.'"'.
                   5125: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   5126: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       5127: 	$ctr++;
                   5128:     }
1.700     bisitz   5129:     $select.= '</select>';
1.68      ng       5130: 
1.700     bisitz   5131:     $result.=
                   5132:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   5133:        .$select
                   5134:        .&Apache::lonhtmlcommon::row_closure();
                   5135: 
                   5136:     $result.=
                   5137:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   5138:        .'<label><input type="radio" name="vProb" value="no"'
                   5139:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   5140:        .'<label><input type="radio" name="vProb" value="yes" />'
                   5141:            .&mt('yes').'</label>'."\n"
                   5142:        .&Apache::lonhtmlcommon::row_closure();
                   5143: 
                   5144:     $result.=
                   5145:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   5146:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   5147:            .&mt('none').' </label>'."\n"
                   5148:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   5149:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   5150:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   5151:            .&mt('all submissions with details').' </label>'
                   5152:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 5153:     
1.700     bisitz   5154:     $result.=
                   5155:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   5156:        .'<input type="text" name="CODE" value="" />'
                   5157:        .&Apache::lonhtmlcommon::row_closure(1)
                   5158:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5159: 
1.700     bisitz   5160:     # Show list of students to select for grading
                   5161:     $result.='<br /><input type="button" '.
1.589     bisitz   5162:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5163: 
1.68      ng       5164:     $request->print($result);
                   5165: 
1.485     albertel 5166:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5167: 	&Apache::loncommon::start_data_table().
                   5168: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5169: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5170: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5171: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5172: 	'<th>'.&nameUserString('header').'</th>'.
                   5173: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5174:  
1.761     raeburn  5175:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5176:     my $ptr = 1;
1.294     albertel 5177:     foreach my $student (sort 
                   5178: 			 {
                   5179: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5180: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5181: 			     }
                   5182: 			     return $a cmp $b;
                   5183: 			 } (keys(%$fullname))) {
1.68      ng       5184: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5185: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5186:                                   : '</td>');
1.126     ng       5187: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5188: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5189: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5190: 	$studentTable.=
                   5191: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5192:                          : '');
1.68      ng       5193: 	$ptr++;
                   5194:     }
1.484     albertel 5195:     if ($ptr%2 == 0) {
                   5196: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5197: 	    &Apache::loncommon::end_data_table_row();
                   5198:     }
                   5199:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5200:     $studentTable.='<input type="button" '.
1.589     bisitz   5201:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5202: 
                   5203:     $request->print($studentTable);
                   5204: 
                   5205:     return '';
                   5206: }
                   5207: 
                   5208: sub getSymbMap {
1.582     raeburn  5209:     my ($map_error) = @_;
1.132     bowersj2 5210:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5211:     unless (ref($navmap)) {
                   5212:         if (ref($map_error)) {
                   5213:             $$map_error = 'navmap';
                   5214:         }
                   5215:         return;
                   5216:     }
1.68      ng       5217:     my %symbx = ();
                   5218:     my @titles = ();
1.117     bowersj2 5219:     my $minder = 0;
                   5220: 
                   5221:     # Gather every sequence that has problems.
1.240     albertel 5222:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5223: 					       1,0,1);
1.117     bowersj2 5224:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5225: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5226: 	    my $title = $minder.'.'.
                   5227: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5228: 	    push(@titles, $title); # minder in case two titles are identical
                   5229: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5230: 	    $minder++;
1.241     albertel 5231: 	}
1.68      ng       5232:     }
                   5233:     return \@titles,\%symbx;
                   5234: }
                   5235: 
1.72      ng       5236: #
                   5237: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5238: sub displayPage {
1.608     www      5239:     my ($request,$symb) = @_;
1.257     albertel 5240:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5241:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5242:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5243:     my $pageTitle = $env{'form.page'};
1.103     albertel 5244:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5245:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5246:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5247: 
                   5248:     #need to make sure we have the correct data for later EXT calls, 
                   5249:     #thus invalidate the cache
                   5250:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5251:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5252:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5253:     &Apache::lonnet::clear_EXT_cache_status();
                   5254: 
1.103     albertel 5255:     if (!&canview($usec)) {
1.712     bisitz   5256:         $request->print(
                   5257:             '<span class="LC_warning">'.
                   5258:             &mt('Unable to view requested student. ([_1])',
                   5259:                     $env{'form.student'}).
                   5260:             '</span>');
                   5261:         return;
1.103     albertel 5262:     }
1.398     albertel 5263:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5264:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5265: 	'</h3>'."\n";
1.500     albertel 5266:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5267:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5268: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5269:     } else {
                   5270: 	delete($env{'form.CODE'});
                   5271:     }
1.71      ng       5272:     &sub_page_js($request);
                   5273:     $request->print($result);
                   5274: 
1.132     bowersj2 5275:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5276:     unless (ref($navmap)) {
                   5277:         $request->print(&navmap_errormsg());
                   5278:         return;
                   5279:     }
1.257     albertel 5280:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5281:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5282:     if (!$map) {
1.485     albertel 5283: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5284: 	return; 
                   5285:     }
1.68      ng       5286:     my $iterator = $navmap->getIterator($map->map_start(),
                   5287: 					$map->map_finish());
                   5288: 
1.71      ng       5289:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5290: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5291: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5292: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5293: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5294: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5295: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5296: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5297: 
1.382     albertel 5298:     if (defined($env{'form.CODE'})) {
                   5299: 	$studentTable.=
                   5300: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5301:     }
1.381     albertel 5302:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5303: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5304: 
1.594     bisitz   5305:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5306:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5307:         '</span>'."\n".
1.484     albertel 5308: 	&Apache::loncommon::start_data_table().
                   5309: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5310: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5311: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5312: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5313: 
1.329     albertel 5314:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5315:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5316:     $iterator->next(); # skip the first BEGIN_MAP
                   5317:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5318:     while ($depth > 0) {
1.68      ng       5319:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5320:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5321: 
1.745     raeburn  5322:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5323: 	    my $parts = $curRes->parts();
1.68      ng       5324:             my $title = $curRes->compTitle();
1.71      ng       5325: 	    my $symbx = $curRes->symb();
1.746     raeburn  5326:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5327: 	    $studentTable.=
                   5328: 		&Apache::loncommon::start_data_table_row().
                   5329: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5330: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5331: 		                        : '<br />('.&mt('[_1]parts',
                   5332: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5333: 		 ).
                   5334: 		 '</td>';
1.71      ng       5335: 	    $studentTable.='<td valign="top">';
1.382     albertel 5336: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5337:             if ($is_tool) {
                   5338:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5339:             } else {
1.745     raeburn  5340: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5341: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5342: 					         undef,'both',\%form);
                   5343: 	        } else {
                   5344: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5345: 		    $companswer =~ s|<form(.*?)>||g;
                   5346: 		    $companswer =~ s|</form>||g;
                   5347: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5348: #		        $companswer =~ s/$1/ /ms;
                   5349: #		        $request->print('match='.$1."<br />\n");
                   5350: #		    }
                   5351: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5352: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5353: 		}
1.71      ng       5354: 	    }
                   5355: 
1.257     albertel 5356: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5357: 
1.257     albertel 5358: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5359: 		if ($record{'version'} eq '') {
1.745     raeburn  5360:                     my $msg = &mt('No recorded submission for this problem.');
                   5361:                     if ($is_tool) {
                   5362:                         $msg = &mt('No recorded transactions for this external tool');
                   5363:                     }
                   5364: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5365: 		} else {
1.116     ng       5366: 		    my %responseType = ();
                   5367: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5368: 			my @responseIds =$curRes->responseIds($partid);
                   5369: 			my @responseType =$curRes->responseType($partid);
                   5370: 			my %responseIds;
                   5371: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5372: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5373: 			}
                   5374: 			$responseType{$partid} = \%responseIds;
1.116     ng       5375: 		    }
1.148     albertel 5376: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5377: 		}
1.257     albertel 5378: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5379: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5380:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5381: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5382: 									$env{'request.course.id'},
1.726     raeburn  5383: 									'','.submission',undef,
                   5384:                                                                         $usec,$identifier);
1.71      ng       5385:  
                   5386: 	    }
1.103     albertel 5387: 	    if (&canmodify($usec)) {
1.585     bisitz   5388:             $studentTable.=&gradeBox_start();
1.103     albertel 5389: 		foreach my $partid (@{$parts}) {
                   5390: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5391: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5392: 		    $question++;
                   5393: 		}
1.585     bisitz   5394:             $studentTable.=&gradeBox_end();
1.196     albertel 5395: 		$prob++;
1.71      ng       5396: 	    }
                   5397: 	    $studentTable.='</td></tr>';
1.68      ng       5398: 
1.103     albertel 5399: 	}
1.68      ng       5400:         $curRes = $iterator->next();
                   5401:     }
                   5402: 
1.589     bisitz   5403:     $studentTable.=
                   5404:         '</table>'."\n".
                   5405:         '<input type="button" value="'.&mt('Save').'" '.
                   5406:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5407:         '</form>'."\n";
1.71      ng       5408:     $request->print($studentTable);
                   5409: 
                   5410:     return '';
1.119     ng       5411: }
                   5412: 
                   5413: sub displaySubByDates {
1.148     albertel 5414:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5415:     my $isCODE=0;
1.335     albertel 5416:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5417:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5418:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5419:     my $studentTable=&Apache::loncommon::start_data_table().
                   5420: 	&Apache::loncommon::start_data_table_header_row().
                   5421: 	'<th>'.&mt('Date/Time').'</th>'.
                   5422: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5423:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5424: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5425: 	'<th>'.&mt('Status').'</th>'.
                   5426: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5427:     my ($version);
                   5428:     my %mark;
1.148     albertel 5429:     my %orders;
1.119     ng       5430:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5431:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5432:         if ($is_tool) {
                   5433:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5434:         } else {
                   5435:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5436:         }
1.147     albertel 5437:     }
1.335     albertel 5438: 
                   5439:     my $interaction;
1.525     raeburn  5440:     my $no_increment = 1;
1.735     raeburn  5441:     my (%lastrndseed,%lasttype);
1.119     ng       5442:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5443: 	my $timestamp = 
                   5444: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5445: 	if (exists($$record{$version.':resource.0.version'})) {
                   5446: 	    $interaction = $$record{$version.':resource.0.version'};
                   5447: 	}
1.671     raeburn  5448:         if ($isTask && $env{'form.previousversion'}) {
                   5449:             next unless ($interaction == $env{'form.previousversion'});
                   5450:         }
1.335     albertel 5451: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5452: 		             : "$version:resource");
1.467     albertel 5453: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5454: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5455: 	if ($isCODE) {
                   5456: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5457: 	}
1.671     raeburn  5458:         if ($isTask) {
                   5459:             $studentTable.='<td>'.$interaction.'</td>';
                   5460:         }
1.119     ng       5461: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5462: 	my @displaySub = ();
                   5463: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5464:             my ($hidden,$type);
                   5465:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5466:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5467:                 $hidden = 1;
                   5468:             }
1.749     raeburn  5469:             my @matchKey;
                   5470:             if ($isTask) {
1.769     raeburn  5471:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5472:             } elsif ($is_tool) {
1.769     raeburn  5473:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5474:             } else {
1.769     raeburn  5475:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5476:             }
1.122     ng       5477: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5478: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5479: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5480: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5481: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5482:                     if ($is_tool) {
                   5483:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5484:                     } else {
1.749     raeburn  5485: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5486: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5487:                         $displaySub[0].='<span class="LC_nobreak">';
                   5488:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5489:                                        .' <span class="LC_internal_info">'
                   5490:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5491:                                        .'</span>'
                   5492:                                        .' <b>';
                   5493:                         if ($hidden) {
                   5494:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5495:                         } else {
                   5496:                             my ($trial,$rndseed,$newvariation);
                   5497:                             if ($type eq 'randomizetry') {
                   5498:                                 $trial = $$record{"$where.$partid.tries"};
                   5499:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5500:                             }
                   5501: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5502: 			        $displaySub[0].=&mt('Trial not counted');
                   5503: 		            } else {
                   5504: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5505: 					        $$record{"$where.$partid.tries"});
                   5506:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5507:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5508:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5509:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5510:                                     }
1.640     raeburn  5511:                                 }
1.749     raeburn  5512:                                 $lastrndseed{$partid} = $rndseed;
                   5513:                                 $lasttype{$partid} = $type;
                   5514: 		            }
                   5515: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5516:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5517: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5518: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5519: 			        $orders{$partid}->{$responseId}=
                   5520: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5521:                                                $no_increment,$type,$trial,$rndseed);
                   5522: 		            }
                   5523: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5524: 		            $displaySub[0].='&nbsp; '.
                   5525: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5526:                         }
1.596     raeburn  5527:                     }
1.147     albertel 5528: 		}
                   5529: 	    }
1.335     albertel 5530: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5531: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5532: 				    $$record{"$where.$partid.checkedin"},
                   5533: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5534: 					'<br />';
1.335     albertel 5535: 	    }
                   5536: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5537: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5538: 		    lc($$record{"$where.$partid.award"}).' '.
                   5539: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5540: 		    '<br />';
1.749     raeburn  5541: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5542: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5543: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5544: 		}
1.147     albertel 5545: 	    }
1.335     albertel 5546: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5547: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5548: 		unless ($is_tool) {
                   5549: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5550: 		}
1.335     albertel 5551: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5552: 		$displaySub[2].=
1.749     raeburn  5553: 		    $$record{"$version:resource.$partid.regrader"};
                   5554:                 unless ($is_tool) {
                   5555: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5556:                 }
1.147     albertel 5557: 	    }
                   5558: 	}
                   5559: 	# needed because old essay regrader has not parts info
                   5560: 	if (exists $$record{"$version:resource.regrader"}) {
                   5561: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5562: 	}
                   5563: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5564: 	if ($displaySub[2]) {
1.467     albertel 5565: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5566: 	}
1.467     albertel 5567: 	$studentTable.='&nbsp;</td>'.
                   5568: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5569:     }
1.467     albertel 5570:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5571:     return $studentTable;
1.71      ng       5572: }
                   5573: 
                   5574: sub updateGradeByPage {
1.608     www      5575:     my ($request,$symb) = @_;
1.71      ng       5576: 
1.257     albertel 5577:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5578:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5579:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5580:     my $pageTitle = $env{'form.page'};
1.103     albertel 5581:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5582:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5583:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5584:     if (!&canmodify($usec)) {
1.526     raeburn  5585: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5586: 	return;
                   5587:     }
1.398     albertel 5588:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5589:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5590: 	'</h3>'."\n";
1.70      ng       5591: 
1.68      ng       5592:     $request->print($result);
                   5593: 
1.582     raeburn  5594: 
1.132     bowersj2 5595:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5596:     unless (ref($navmap)) {
                   5597:         $request->print(&navmap_errormsg());
                   5598:         return;
                   5599:     }
1.257     albertel 5600:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5601:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5602:     if (!$map) {
1.527     raeburn  5603: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5604: 	return; 
                   5605:     }
1.71      ng       5606:     my $iterator = $navmap->getIterator($map->map_start(),
                   5607: 					$map->map_finish());
1.70      ng       5608: 
1.484     albertel 5609:     my $studentTable=
                   5610: 	&Apache::loncommon::start_data_table().
                   5611: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5612: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5613: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5614: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5615: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5616: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5617: 
                   5618:     $iterator->next(); # skip the first BEGIN_MAP
                   5619:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5620:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5621:     while ($depth > 0) {
1.71      ng       5622:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5623:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5624: 
1.385     albertel 5625:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5626: 	    my $parts = $curRes->parts();
1.71      ng       5627:             my $title = $curRes->compTitle();
                   5628: 	    my $symbx = $curRes->symb();
1.484     albertel 5629: 	    $studentTable.=
                   5630: 		&Apache::loncommon::start_data_table_row().
                   5631: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5632: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5633:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5634: 		.')').'</td>';
1.71      ng       5635: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5636: 
                   5637: 	    my %newrecord=();
                   5638: 	    my @displayPts=();
1.269     raeburn  5639:             my %aggregate = ();
                   5640:             my $aggregateflag = 0;
1.726     raeburn  5641:             if ($env{'form.HIDE'.$prob}) {
                   5642:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5643:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5644:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5645:                 $hideflag += $numchgs;
                   5646:             }
1.71      ng       5647: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5648: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5649: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5650: 
1.257     albertel 5651: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5652: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5653: 		my $partial = $newpts/$wgt;
                   5654: 		my $score;
                   5655: 		if ($partial > 0) {
                   5656: 		    $score = 'correct_by_override';
1.125     ng       5657: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5658: 		    $score = 'incorrect_by_override';
                   5659: 		}
1.257     albertel 5660: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5661: 		if ($dropMenu eq 'excused') {
1.71      ng       5662: 		    $partial = '';
                   5663: 		    $score = 'excused';
1.125     ng       5664: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5665: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5666: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5667: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5668: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5669: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5670: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5671: 		    $changeflag++;
                   5672: 		    $newpts = '';
1.269     raeburn  5673:                     
                   5674:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5675:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5676:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5677:                     if ($aggtries > 0) {
                   5678:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5679:                         $aggregateflag = 1;
                   5680:                     }
1.71      ng       5681: 		}
1.324     albertel 5682: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5683: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5684: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5685: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5686: 		    '&nbsp;<br />';
1.526     raeburn  5687: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5688: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5689: 		    '&nbsp;<br />';
1.71      ng       5690: 		$question++;
1.380     albertel 5691: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5692: 
1.71      ng       5693: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5694: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5695: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5696: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5697: 
                   5698: 		$changeflag++;
                   5699: 	    }
                   5700: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5701: 		my %record = 
                   5702: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5703: 					     $udom,$uname);
                   5704: 
                   5705: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5706: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5707: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5708: 		    $newrecord{'resource.CODE'} = '';
                   5709: 		}
1.257     albertel 5710: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5711: 					$udom,$uname);
1.382     albertel 5712: 		%record = &Apache::lonnet::restore($symbx,
                   5713: 						   $env{'request.course.id'},
                   5714: 						   $udom,$uname);
1.380     albertel 5715: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5716: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5717: 	    }
1.380     albertel 5718: 	    
1.269     raeburn  5719:             if ($aggregateflag) {
                   5720:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5721:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5722:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5723:             }
1.125     ng       5724: 
1.71      ng       5725: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5726: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5727: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5728: 
1.196     albertel 5729: 	    $prob++;
1.68      ng       5730: 	}
1.71      ng       5731:         $curRes = $iterator->next();
1.68      ng       5732:     }
1.98      albertel 5733: 
1.484     albertel 5734:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5735:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5736: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5737: 		  $changeflag).'<br />');
                   5738:     my $hidemsg=($hideflag == 0 ? '' :
                   5739:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5740:                      $hideflag).'<br />');
                   5741:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5742: 
1.70      ng       5743:     return '';
                   5744: }
                   5745: 
1.72      ng       5746: #-------- end of section for handling grading by page/sequence ---------
                   5747: #
                   5748: #-------------------------------------------------------------------
                   5749: 
1.581     www      5750: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5751: #
                   5752: #------ start of section for handling grading by page/sequence ---------
                   5753: 
1.423     albertel 5754: =pod
                   5755: 
                   5756: =head1 Bubble sheet grading routines
                   5757: 
1.424     albertel 5758:   For this documentation:
                   5759: 
                   5760:    'scanline' refers to the full line of characters
                   5761:    from the file that we are parsing that represents one entire sheet
                   5762: 
                   5763:    'bubble line' refers to the data
1.659     raeburn  5764:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5765: 
                   5766: 
1.659     raeburn  5767: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5768: into a course. When a user wants to grade, they select a
1.659     raeburn  5769: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5770: one of the predefined configurations for what each scanline looks
                   5771: like.
                   5772: 
                   5773: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5774: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5775: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5776: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5777: invalid student/employee ID
1.424     albertel 5778: 
                   5779: If the CODE option is used that determines the randomization of the
1.556     weissno  5780: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5781: username:domain.
                   5782: 
                   5783: During the validation phase the instructor can choose to skip scanlines. 
                   5784: 
1.659     raeburn  5785: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5786: 
                   5787:   scantron_original_filename (unmodified original file)
                   5788:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5789:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5790: 
                   5791: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5792: correction information that isn't representable in the bubblesheet
1.424     albertel 5793: file (see &scantron_getfile() for more information)
                   5794: 
                   5795: After all scanlines are either valid, marked as valid or skipped, then
                   5796: foreach line foreach problem in the picked sequence, an ssi request is
                   5797: made that simulates a user submitting their selected letter(s) against
                   5798: the homework problem.
1.423     albertel 5799: 
                   5800: =over 4
                   5801: 
                   5802: 
                   5803: 
                   5804: =item defaultFormData
                   5805: 
                   5806:   Returns html hidden inputs used to hold context/default values.
                   5807: 
                   5808:  Arguments:
                   5809:   $symb - $symb of the current resource 
                   5810: 
                   5811: =cut
1.422     foxr     5812: 
1.81      albertel 5813: sub defaultFormData {
1.324     albertel 5814:     my ($symb)=@_;
1.766     raeburn  5815:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5816: }
                   5817: 
1.447     foxr     5818: 
1.423     albertel 5819: =pod 
                   5820: 
                   5821: =item getSequenceDropDown
                   5822: 
                   5823:    Return html dropdown of possible sequences to grade
                   5824:  
                   5825:  Arguments:
1.582     raeburn  5826:    $symb - $symb of the current resource
                   5827:    $map_error - ref to scalar which will container error if
                   5828:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5829: 
                   5830: =cut
1.422     foxr     5831: 
1.75      albertel 5832: sub getSequenceDropDown {
1.582     raeburn  5833:     my ($symb,$map_error)=@_;
1.75      albertel 5834:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5835:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5836:     if (ref($map_error)) {
                   5837:         return if ($$map_error);
                   5838:     }
1.137     albertel 5839:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5840:     my $ctr=0;
                   5841:     foreach (@$titles) {
                   5842: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5843: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5844: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5845: 	    '>'.$showtitle.'</option>'."\n";
                   5846: 	$ctr++;
                   5847:     }
                   5848:     $result.= '</select>';
                   5849:     return $result;
                   5850: }
                   5851: 
1.495     albertel 5852: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5853:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5854: 
                   5855: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5856: 
1.509     raeburn  5857: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5858:                                    # matchresponse or rankresponse, where 
                   5859:                                    # an individual response can have multiple 
                   5860:                                    # lines
1.503     raeburn  5861: 
                   5862: my %responsetype_per_response;     # responsetype for each response
                   5863: 
1.691     raeburn  5864: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5865:                                    # numbered response. Needed when randomorder
                   5866:                                    # or randompick are in use. Key is ID, value 
                   5867:                                    # is response number.
                   5868: 
1.495     albertel 5869: # Save and restore the bubble lines array to the form env.
                   5870: 
                   5871: 
                   5872: sub save_bubble_lines {
                   5873:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5874: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5875: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5876: 	    $first_bubble_line{$line};
1.503     raeburn  5877:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5878:             $subdivided_bubble_lines{$line};
                   5879:         $env{"form.scantron.responsetype.$line"} =
                   5880:             $responsetype_per_response{$line};
1.495     albertel 5881:     }
1.691     raeburn  5882:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5883:         my $line = $masterseq_id_responsenum{$resid};
                   5884:         $env{"form.scantron.residpart.$line"} = $resid;
                   5885:     }
1.495     albertel 5886: }
                   5887: 
                   5888: 
                   5889: sub restore_bubble_lines {
                   5890:     my $line = 0;
                   5891:     %bubble_lines_per_response = ();
1.691     raeburn  5892:     %masterseq_id_responsenum = ();
1.495     albertel 5893:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5894: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5895: 	$bubble_lines_per_response{$line} = $value;
                   5896: 	$first_bubble_line{$line}  =
                   5897: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5898:         $subdivided_bubble_lines{$line} =
                   5899:             $env{"form.scantron.sub_bubblelines.$line"};
                   5900:         $responsetype_per_response{$line} =
                   5901:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5902:         my $id = $env{"form.scantron.residpart.$line"};
                   5903:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5904: 	$line++;
                   5905:     }
                   5906: }
                   5907: 
1.423     albertel 5908: =pod 
                   5909: 
                   5910: =item scantron_filenames
                   5911: 
                   5912:    Returns a list of the scantron files in the current course 
                   5913: 
                   5914: =cut
1.422     foxr     5915: 
1.202     albertel 5916: sub scantron_filenames {
1.257     albertel 5917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5918:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5919:     my $getpropath = 1;
1.662     raeburn  5920:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5921:                                                         $cname,$getpropath);
1.202     albertel 5922:     my @possiblenames;
1.662     raeburn  5923:     if (ref($dirlist) eq 'ARRAY') {
                   5924:         foreach my $filename (sort(@{$dirlist})) {
                   5925: 	    ($filename)=split(/&/,$filename);
                   5926: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5927: 	    $filename=~s/^scantron_orig_//;
                   5928: 	    push(@possiblenames,$filename);
                   5929:         }
1.202     albertel 5930:     }
                   5931:     return @possiblenames;
                   5932: }
                   5933: 
1.423     albertel 5934: =pod 
                   5935: 
                   5936: =item scantron_uploads
                   5937: 
                   5938:    Returns  html drop-down list of scantron files in current course.
                   5939: 
                   5940:  Arguments:
                   5941:    $file2grade - filename to set as selected in the dropdown
                   5942: 
                   5943: =cut
1.422     foxr     5944: 
1.202     albertel 5945: sub scantron_uploads {
1.209     ng       5946:     my ($file2grade) = @_;
1.202     albertel 5947:     my $result=	'<select name="scantron_selectfile">';
                   5948:     $result.="<option></option>";
                   5949:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5950: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5951:     }
                   5952:     $result.="</select>";
                   5953:     return $result;
                   5954: }
                   5955: 
1.423     albertel 5956: =pod 
                   5957: 
                   5958: =item scantron_scantab
                   5959: 
                   5960:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5961:   file.
                   5962: 
                   5963: =cut
1.422     foxr     5964: 
1.82      albertel 5965: sub scantron_scantab {
                   5966:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5967:     $result.='<option></option>'."\n";
1.754     raeburn  5968:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5969:     if (@lines > 0) {
                   5970:         foreach my $line (@lines) {
                   5971:             next if (($line =~ /^\#/) || ($line eq ''));
                   5972: 	    my ($name,$descrip)=split(/:/,$line);
                   5973: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5974:         }
1.82      albertel 5975:     }
                   5976:     $result.='</select>'."\n";
1.518     raeburn  5977:     return $result;
                   5978: }
                   5979: 
1.423     albertel 5980: =pod 
                   5981: 
                   5982: =item scantron_CODElist
                   5983: 
                   5984:   Returns html drop down of the saved CODE lists from current course,
                   5985:   generated from earlier printings.
                   5986: 
                   5987: =cut
1.422     foxr     5988: 
1.186     albertel 5989: sub scantron_CODElist {
1.257     albertel 5990:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5991:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5992:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5993:     my $namechoice='<option></option>';
1.225     albertel 5994:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5995: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5996: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5997: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5998:     }
                   5999:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   6000:     return $namechoice;
                   6001: }
                   6002: 
1.423     albertel 6003: =pod 
                   6004: 
                   6005: =item scantron_CODEunique
                   6006: 
                   6007:   Returns the html for "Each CODE to be used once" radio.
                   6008: 
                   6009: =cut
1.422     foxr     6010: 
1.186     albertel 6011: sub scantron_CODEunique {
1.532     bisitz   6012:     my $result='<span class="LC_nobreak">
1.272     albertel 6013:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6014:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 6015:                 </span>
1.532     bisitz   6016:                 <span class="LC_nobreak">
1.272     albertel 6017:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 6018:                         value="no" />'.&mt('No').' </label>
1.381     albertel 6019:                 </span>';
1.186     albertel 6020:     return $result;
                   6021: }
1.423     albertel 6022: 
                   6023: =pod 
                   6024: 
                   6025: =item scantron_selectphase
                   6026: 
1.659     raeburn  6027:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 6028:   Allows for - starting a grading run.
1.424     albertel 6029:              - downloading existing scan data (original, corrected
1.423     albertel 6030:                                                 or skipped info)
                   6031: 
                   6032:              - uploading new scan data
                   6033: 
                   6034:  Arguments:
                   6035:   $r          - The Apache request object
                   6036:   $file2grade - name of the file that contain the scanned data to score
                   6037: 
                   6038: =cut
1.186     albertel 6039: 
1.75      albertel 6040: sub scantron_selectphase {
1.608     www      6041:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 6042:     if (!$symb) {return '';}
1.582     raeburn  6043:     my $map_error;
                   6044:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   6045:     if ($map_error) {
                   6046:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   6047:         return;
                   6048:     }
1.324     albertel 6049:     my $default_form_data=&defaultFormData($symb);
1.209     ng       6050:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 6051:     my $format_selector=&scantron_scantab();
1.186     albertel 6052:     my $CODE_selector=&scantron_CODElist();
                   6053:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 6054:     my $result;
1.422     foxr     6055: 
1.513     foxr     6056:     $ssi_error = 0;
                   6057: 
1.770     raeburn  6058:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 6059: 
                   6060: 	# Chunk of form to prompt for a scantron file upload.
                   6061: 
                   6062:         $r->print('
1.754     raeburn  6063:     <br />');
1.606     wenzelju 6064:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6065:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  6066:     my $csec= $env{'request.course.sec'};
1.736     damieng  6067:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   6068:     &js_escape(\$alertmsg);
1.754     raeburn  6069:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 6070:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   6071:     function checkUpload(formname) {
                   6072: 	if (formname.upfile.value == "") {
1.736     damieng  6073: 	    alert("'.$alertmsg.'");
1.606     wenzelju 6074: 	    return false;
                   6075: 	}
                   6076: 	formname.submit();
1.756     raeburn  6077:     }'."\n".$formatjs));
1.606     wenzelju 6078:     $r->print('
                   6079:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   6080:                 '.$default_form_data.'
                   6081:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  6082:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 6083:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   6084:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  6085:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6086:               '.&Apache::loncommon::start_data_table_header_row().'
                   6087:                 <th>
                   6088:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   6089:                 </th>
                   6090:               '.&Apache::loncommon::end_data_table_header_row().'
                   6091:               '.&Apache::loncommon::start_data_table_row().'
                   6092:             <td>
                   6093:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   6094:     if ($formatoptions) {
                   6095:         $r->print('</td>
                   6096:                  '.&Apache::loncommon::end_data_table_row().'
                   6097:                  '.&Apache::loncommon::start_data_table_row().'
                   6098:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   6099:                  </td>
                   6100:                  '.&Apache::loncommon::end_data_table_row().'
                   6101:                  '.&Apache::loncommon::start_data_table_row().'
                   6102:                  <td>'
                   6103:         );
                   6104:     } else {
                   6105:         $r->print(' <br />');
                   6106:     }
                   6107:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   6108:               </td>
                   6109:              '.&Apache::loncommon::end_data_table_row().'
                   6110:              '.&Apache::loncommon::end_data_table().'
                   6111:              </form>'
                   6112:     );
1.606     wenzelju 6113: 
                   6114:     }
                   6115: 
1.422     foxr     6116:     # Chunk of form to prompt for a file to grade and how:
                   6117: 
1.489     albertel 6118:     $result.= '
                   6119:     <br />
                   6120:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   6121:     <input type="hidden" name="command" value="scantron_warning" />
                   6122:     '.$default_form_data.'
                   6123:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6124:        '.&Apache::loncommon::start_data_table_header_row().'
                   6125:             <th colspan="2">
1.492     albertel 6126:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 6127:             </th>
                   6128:        '.&Apache::loncommon::end_data_table_header_row().'
                   6129:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6130:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 6131:        '.&Apache::loncommon::end_data_table_row().'
                   6132:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6133:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 6134:        '.&Apache::loncommon::end_data_table_row().'
                   6135:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      6136:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 6137:        '.&Apache::loncommon::end_data_table_row().'
                   6138:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6139:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 6140:        '.&Apache::loncommon::end_data_table_row().'
                   6141:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6142:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 6143:        '.&Apache::loncommon::end_data_table_row().'
                   6144:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6145: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 6146:             <td>
1.492     albertel 6147: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   6148:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   6149:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 6150: 	    </td>
1.489     albertel 6151:        '.&Apache::loncommon::end_data_table_row().'
                   6152:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 6153:             <td colspan="2">
1.572     www      6154:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 6155:             </td>
1.489     albertel 6156:        '.&Apache::loncommon::end_data_table_row().'
                   6157:     '.&Apache::loncommon::end_data_table().'
                   6158:     </form>
                   6159: ';
1.162     albertel 6160:    
                   6161:     $r->print($result);
                   6162: 
1.422     foxr     6163:     # Chunk of the form that prompts to view a scoring office file,
                   6164:     # corrected file, skipped records in a file.
                   6165: 
1.489     albertel 6166:     $r->print('
                   6167:    <br />
                   6168:    <form action="/adm/grades" name="scantron_download">
                   6169:      '.$default_form_data.'
                   6170:      <input type="hidden" name="command" value="scantron_download" />
                   6171:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6172:        '.&Apache::loncommon::start_data_table_header_row().'
                   6173:               <th>
1.492     albertel 6174:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6175:               </th>
                   6176:        '.&Apache::loncommon::end_data_table_header_row().'
                   6177:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6178:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6179:                 <br />
1.492     albertel 6180:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6181:        '.&Apache::loncommon::end_data_table_row().'
                   6182:      '.&Apache::loncommon::end_data_table().'
                   6183:    </form>
                   6184:    <br />
                   6185: ');
1.162     albertel 6186: 
1.457     banghart 6187:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6188: 
1.694     bisitz   6189:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6190:              $default_form_data."\n".
                   6191:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6192:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6193:              '<th colspan="2">
1.572     www      6194:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6195:              '</th>'."\n".
                   6196:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6197:               &Apache::loncommon::start_data_table_row()."\n".
                   6198:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6199:               '<td> '.$sequence_selector.' </td>'.
                   6200:               &Apache::loncommon::end_data_table_row()."\n".
                   6201:               &Apache::loncommon::start_data_table_row()."\n".
                   6202:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6203:               '<td> '.$file_selector.' </td>'."\n".
                   6204:               &Apache::loncommon::end_data_table_row()."\n".
                   6205:               &Apache::loncommon::start_data_table_row()."\n".
                   6206:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6207:               '<td> '.$format_selector.' </td>'."\n".
                   6208:               &Apache::loncommon::end_data_table_row()."\n".
                   6209:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6210:               '<td> '.&mt('Options').' </td>'."\n".
                   6211:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6212:               &Apache::loncommon::end_data_table_row()."\n".
                   6213:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6214:               '<td colspan="2">'."\n".
                   6215:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6216:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6217:               '</td>'."\n".
                   6218:               &Apache::loncommon::end_data_table_row()."\n".
                   6219:               &Apache::loncommon::end_data_table()."\n".
                   6220:               '</form><br />');
                   6221:     return;
1.75      albertel 6222: }
                   6223: 
1.423     albertel 6224: =pod 
                   6225: 
                   6226: =item username_to_idmap
                   6227: 
1.556     weissno  6228:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6229:     student username:domain. If a single ID occurs for more than one student,
                   6230:     the status of the student is checked, and if Active, the value in the hash
                   6231:     will be set to the Active student.
1.423     albertel 6232: 
                   6233:   Arguments:
                   6234: 
                   6235:     $classlist - reference to the class list hash. This is a hash
                   6236:                  keyed by student name:domain  whose elements are references
1.424     albertel 6237:                  to arrays containing various chunks of information
1.423     albertel 6238:                  about the student. (See loncoursedata for more info).
                   6239: 
                   6240:   Returns
                   6241:     %idmap - the constructed hash
                   6242: 
                   6243: =cut
                   6244: 
1.82      albertel 6245: sub username_to_idmap {
                   6246:     my ($classlist)= @_;
                   6247:     my %idmap;
                   6248:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6249:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6250:         unless ($id eq '') {
                   6251:             if (!exists($idmap{$id})) {
                   6252:                 $idmap{$id} = $student;
                   6253:             } else {
                   6254:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6255:                 if ($status eq 'Active') {
                   6256:                     $idmap{$id} = $student;
                   6257:                 }
                   6258:             }
                   6259:         }
1.82      albertel 6260:     }
                   6261:     return %idmap;
                   6262: }
1.423     albertel 6263: 
                   6264: =pod
                   6265: 
1.424     albertel 6266: =item scantron_fixup_scanline
1.423     albertel 6267: 
                   6268:    Process a requested correction to a scanline.
                   6269: 
                   6270:   Arguments:
1.754     raeburn  6271:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6272:     $scan_data         - hash of correction information 
                   6273:                           (see &scantron_getfile())
                   6274:     $line              - existing scanline
                   6275:     $whichline         - line number of the passed in scanline
                   6276:     $field             - type of change to process 
                   6277:                          (either 
1.573     bisitz   6278:                           'ID'     -> correct the student/employee ID
1.423     albertel 6279:                           'CODE'   -> correct the CODE
                   6280:                           'answer' -> fixup the submitted answers)
                   6281:     
                   6282:    $args               - hash of additional info,
                   6283:                           - 'ID' 
                   6284:                                'newid' -> studentID to use in replacement
1.424     albertel 6285:                                           of existing one
1.423     albertel 6286:                           - 'CODE' 
                   6287:                                'CODE_ignore_dup' - set to true if duplicates
                   6288:                                                    should be ignored.
                   6289: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6290:                                         if the existing unfound code should
1.423     albertel 6291:                                         be used as is
                   6292:                           - 'answer'
                   6293:                                'response' - new answer or 'none' if blank
                   6294:                                'question' - the bubble line to change
1.503     raeburn  6295:                                'questionnum' - the question identifier,
                   6296:                                                may include subquestion. 
1.423     albertel 6297: 
                   6298:   Returns:
                   6299:     $line - the modified scanline
                   6300: 
                   6301:   Side effects: 
                   6302:     $scan_data - may be updated
                   6303: 
                   6304: =cut
                   6305: 
1.82      albertel 6306: 
1.157     albertel 6307: sub scantron_fixup_scanline {
                   6308:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6309:     if ($field eq 'ID') {
                   6310: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6311: 	    return ($line,1,'New value too large');
1.157     albertel 6312: 	}
                   6313: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6314: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6315: 				     $args->{'newid'});
                   6316: 	}
                   6317: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6318: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6319: 	if ($args->{'newid'}=~/^\s*$/) {
                   6320: 	    &scan_data($scan_data,"$whichline.user",
                   6321: 		       $args->{'username'}.':'.$args->{'domain'});
                   6322: 	}
1.186     albertel 6323:     } elsif ($field eq 'CODE') {
1.192     albertel 6324: 	if ($args->{'CODE_ignore_dup'}) {
                   6325: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6326: 	}
                   6327: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6328: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6329: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6330: 		return ($line,1,'New CODE value too large');
                   6331: 	    }
                   6332: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6333: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6334: 	    }
                   6335: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6336: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6337: 	}
1.157     albertel 6338:     } elsif ($field eq 'answer') {
1.497     foxr     6339: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6340: 	my $off=$scantron_config->{'Qoff'};
                   6341: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6342: 	my $answer=${off}x$length;
                   6343: 	if ($args->{'response'} eq 'none') {
                   6344: 	    &scan_data($scan_data,
1.503     raeburn  6345: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6346: 	} else {
                   6347: 	    if ($on eq 'letter') {
                   6348: 		my @alphabet=('A'..'Z');
                   6349: 		$answer=$alphabet[$args->{'response'}];
                   6350: 	    } elsif ($on eq 'number') {
                   6351: 		$answer=$args->{'response'}+1;
                   6352: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6353: 	    } else {
1.497     foxr     6354: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6355: 	    }
1.497     foxr     6356: 	    &scan_data($scan_data,
1.503     raeburn  6357: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6358: 	}
1.497     foxr     6359: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6360: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6361:     }
                   6362:     return $line;
                   6363: }
1.423     albertel 6364: 
                   6365: =pod
                   6366: 
                   6367: =item scan_data
                   6368: 
                   6369:     Edit or look up  an item in the scan_data hash.
                   6370: 
                   6371:   Arguments:
                   6372:     $scan_data  - The hash (see scantron_getfile)
                   6373:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6374:                   scantronfilename_key).
1.423     albertel 6375:     $data        - New value of the hash entry.
                   6376:     $delete      - If true, the entry is removed from the hash.
                   6377: 
                   6378:   Returns:
                   6379:     The new value of the hash table field (undefined if deleted).
                   6380: 
                   6381: =cut
                   6382: 
                   6383: 
1.157     albertel 6384: sub scan_data {
                   6385:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6386:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6387:     if (defined($value)) {
                   6388: 	$scan_data->{$filename.'_'.$key} = $value;
                   6389:     }
                   6390:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6391:     return $scan_data->{$filename.'_'.$key};
                   6392: }
1.423     albertel 6393: 
1.495     albertel 6394: # ----- These first few routines are general use routines.----
                   6395: 
                   6396: # Return the number of occurences of a pattern in a string.
                   6397: 
                   6398: sub occurence_count {
                   6399:     my ($string, $pattern) = @_;
                   6400: 
                   6401:     my @matches = ($string =~ /$pattern/g);
                   6402: 
                   6403:     return scalar(@matches);
                   6404: }
                   6405: 
                   6406: 
                   6407: # Take a string known to have digits and convert all the
                   6408: # digits into letters in the range J,A..I.
                   6409: 
                   6410: sub digits_to_letters {
                   6411:     my ($input) = @_;
                   6412: 
                   6413:     my @alphabet = ('J', 'A'..'I');
                   6414: 
                   6415:     my @input    = split(//, $input);
                   6416:     my $output ='';
                   6417:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6418: 	if ($input[$i] =~ /\d/) {
                   6419: 	    $output .= $alphabet[$input[$i]];
                   6420: 	} else {
                   6421: 	    $output .= $input[$i];
                   6422: 	}
                   6423:     }
                   6424:     return $output;
                   6425: }
                   6426: 
1.423     albertel 6427: =pod 
                   6428: 
                   6429: =item scantron_parse_scanline
                   6430: 
1.711     bisitz   6431:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6432: 
                   6433:  Arguments:
1.711     bisitz   6434:     line             - The text of the bubblesheet file line to process
1.423     albertel 6435:     whichline        - Line number
1.711     bisitz   6436:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6437:     scan_data        - Hash of extra information about the scanline
                   6438:                        (see scantron_getfile for more information)
                   6439:     just_header      - True if should not process question answers but only
                   6440:                        the stuff to the left of the answers.
1.691     raeburn  6441:     randomorder      - True if randomorder in use
                   6442:     randompick       - True if randompick in use
                   6443:     sequence         - Exam folder URL
                   6444:     master_seq       - Ref to array containing symbs in exam folder
                   6445:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6446:                        (corresponding values are resource objects)
                   6447:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6448:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6449:                        are refs to an array of resource objects, ordered
                   6450:                        according to order used for CODE, when randomorder
                   6451:                        and or randompick are in use.
                   6452:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6453:                        for current line to question number used for same question
                   6454:                         in "Master Sequence" (as seen by Course Coordinator).
                   6455:     startline        - Ref to hash where key is question number (0 is first)
                   6456:                        and value is number of first bubble line for current 
                   6457:                        student or code-based randompick and/or randomorder.
                   6458:     totalref         - Ref of scalar used to score total number of bubble
                   6459:                        lines needed for responses in a scan line (used when
                   6460:                        randompick in use. 
                   6461:     
1.423     albertel 6462:  Returns:
                   6463:    Hash containing the result of parsing the scanline
                   6464: 
                   6465:    Keys are all proceeded by the string 'scantron.'
                   6466: 
                   6467:        CODE    - the CODE in use for this scanline
                   6468:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6469:                  by the operator
                   6470:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6471:                             CODEs were selected, but the usage has been
                   6472:                             forced by the operator
1.556     weissno  6473:        ID  - student/employee ID
1.423     albertel 6474:        PaperID - if used, the ID number printed on the sheet when the 
                   6475:                  paper was scanned
                   6476:        FirstName - first name from the sheet
                   6477:        LastName  - last name from the sheet
                   6478: 
                   6479:      if just_header was not true these key may also exist
                   6480: 
1.447     foxr     6481:        missingerror - a list of bubble ranges that are considered to be answers
                   6482:                       to a single question that don't have any bubbles filled in.
                   6483:                       Of the form questionnumber:firstbubblenumber:count.
                   6484:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6485:                       to a single question that have more than one bubble filled in.
                   6486:                       Of the form questionnumber::firstbubblenumber:count
                   6487:    
                   6488:                 In the above, count is the number of bubble responses in the
                   6489:                 input line needed to represent the possible answers to the question.
                   6490:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6491:                 per line would have count = 2.
                   6492: 
1.423     albertel 6493:        maxquest     - the number of the last bubble line that was parsed
                   6494: 
                   6495:        (<number> starts at 1)
                   6496:        <number>.answer - zero or more letters representing the selected
                   6497:                          letters from the scanline for the bubble line 
                   6498:                          <number>.
                   6499:                          if blank there was either no bubble or there where
                   6500:                          multiple bubbles, (consult the keys missingerror and
                   6501:                          doubleerror if this is an error condition)
                   6502: 
                   6503: =cut
                   6504: 
1.82      albertel 6505: sub scantron_parse_scanline {
1.691     raeburn  6506:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6507:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6508:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6509: 
1.82      albertel 6510:     my %record;
1.691     raeburn  6511:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6512:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6513: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6514: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6515: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6516: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6517: 	    $record{'scantron.CODE'}=substr($data,
                   6518: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6519: 					    $$scantron_config{'CODElength'});
1.191     albertel 6520: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6521: 		$record{'scantron.useCODE'}=1;
                   6522: 	    }
1.192     albertel 6523: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6524: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6525: 	    }
1.82      albertel 6526: 	} else {
                   6527: 	    #FIXME interpret first N questions
                   6528: 	}
                   6529:     }
1.83      albertel 6530:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6531: 				  $$scantron_config{'IDlength'});
1.157     albertel 6532:     $record{'scantron.PaperID'}=
                   6533: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6534: 	       $$scantron_config{'PaperIDlength'});
                   6535:     $record{'scantron.FirstName'}=
                   6536: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6537: 	       $$scantron_config{'FirstNamelength'});
                   6538:     $record{'scantron.LastName'}=
                   6539: 	substr($data,$$scantron_config{'LastName'}-1,
                   6540: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6541:     if ($just_header) { return \%record; }
1.194     albertel 6542: 
1.82      albertel 6543:     my @alphabet=('A'..'Z');
                   6544:     my $questnum=0;
1.447     foxr     6545:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6546: 
1.691     raeburn  6547:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6548:     if ($randompick || $randomorder) {
                   6549:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6550:                                          $master_seq,$symb_to_resource,
                   6551:                                          $partids_by_symb,$orderedforcode,
                   6552:                                          $respnumlookup,$startline);
                   6553:         if ($total) {
                   6554:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6555:         }
                   6556:         if (ref($totalref)) {
                   6557:             $$totalref = $total;
                   6558:         }
                   6559:     }
                   6560:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6561:     chomp($questions);		# Get rid of any trailing \n.
                   6562:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6563:     while (length($questions)) {
1.691     raeburn  6564:         my $answers_needed;
                   6565:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6566:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6567:         } else {
                   6568: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6569:         }
1.503     raeburn  6570:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6571:                              || 1;
                   6572:         $questnum++;
                   6573:         my $quest_id = $questnum;
                   6574:         my $currentquest = substr($questions,0,$answer_length);
                   6575:         $questions       = substr($questions,$answer_length);
                   6576:         if (length($currentquest) < $answer_length) { next; }
                   6577: 
1.691     raeburn  6578:         my $subdivided;
                   6579:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6580:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6581:         } else {
                   6582:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6583:         }
                   6584:         if ($subdivided =~ /,/) {
1.503     raeburn  6585:             my $subquestnum = 1;
                   6586:             my $subquestions = $currentquest;
1.691     raeburn  6587:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6588:             foreach my $subans (@subanswers_needed) {
                   6589:                 my $subans_length =
                   6590:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6591:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6592:                 $subquestions   = substr($subquestions,$subans_length);
                   6593:                 $quest_id = "$questnum.$subquestnum";
                   6594:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6595:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6596:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6597:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6598:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6599:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6600:                 } else {
                   6601:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6602:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6603:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6604:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6605:                 }
                   6606:                 $subquestnum ++;
                   6607:             }
                   6608:         } else {
                   6609:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6610:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6611:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6612:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6613:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6614:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6615:             } else {
                   6616:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6617:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6618:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6619:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6620:             }
                   6621:         }
                   6622:     }
                   6623:     $record{'scantron.maxquest'}=$questnum;
                   6624:     return \%record;
                   6625: }
1.447     foxr     6626: 
1.691     raeburn  6627: sub get_master_seq {
                   6628:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6629:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6630:                    (ref($symb_to_resource) eq 'HASH'));
                   6631:     my $resource_error;
                   6632:     foreach my $resource (@{$resources}) {
                   6633:         my $ressymb;
                   6634:         if (ref($resource)) {
                   6635:             $ressymb = $resource->symb();
                   6636:             push(@{$master_seq},$ressymb);
                   6637:             $symb_to_resource->{$ressymb} = $resource;
                   6638:         } else {
                   6639:             $resource_error = 1;
                   6640:             last;
                   6641:         }
                   6642:     }
                   6643:     return $resource_error;
                   6644: }
                   6645: 
                   6646: sub get_respnum_lookups {
                   6647:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6648:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6649:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6650:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6651:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6652:                    (ref($startline) eq 'HASH'));
                   6653:     my ($user,$scancode);
                   6654:     if ((exists($record->{'scantron.CODE'})) &&
                   6655:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6656:         $scancode = $record->{'scantron.CODE'};
                   6657:     } else {
                   6658:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6659:     }
                   6660:     my @mapresources =
                   6661:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6662:                      $orderedforcode);
                   6663:     my $total = 0;
                   6664:     my $count = 0;
                   6665:     foreach my $resource (@mapresources) {
                   6666:         my $id = $resource->id();
                   6667:         my $symb = $resource->symb();
                   6668:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6669:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6670:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6671:                 if ($respnum ne '') {
                   6672:                     $respnumlookup->{$count} = $respnum;
                   6673:                     $startline->{$count} = $total;
                   6674:                     $total += $bubble_lines_per_response{$respnum};
                   6675:                     $count ++;
                   6676:                 }
                   6677:             }
                   6678:         }
                   6679:     }
                   6680:     return $total;
                   6681: }
                   6682: 
1.503     raeburn  6683: sub scantron_validator_lettnum {
                   6684:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6685:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6686:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6687: 
                   6688:     # Qon 'letter' implies for each slot in currquest we have:
                   6689:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6690:     #    about anything else (esp. a value of Qoff) for missing
                   6691:     #    bubbles.
                   6692:     #
                   6693:     # Qon 'number' implies each slot gives a digit that indexes the
                   6694:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6695:     #    and * or ? for double bubbles on a single line.
                   6696:     #
1.447     foxr     6697: 
1.503     raeburn  6698:     my $matchon;
                   6699:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6700:         $matchon = '[A-Z]';
                   6701:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6702:         $matchon = '\d';
                   6703:     }
                   6704:     my $occurrences = 0;
1.691     raeburn  6705:     my $responsenum = $questnum-1;
                   6706:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6707:        $responsenum = $respnumlookup->{$questnum-1} 
                   6708:     }
                   6709:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6710:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6711:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6712:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6713:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6714:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6715:         my @singlelines = split('',$currquest);
                   6716:         foreach my $entry (@singlelines) {
                   6717:             $occurrences = &occurence_count($entry,$matchon);
                   6718:             if ($occurrences > 1) {
                   6719:                 last;
                   6720:             }
1.691     raeburn  6721:         }
1.503     raeburn  6722:     } else {
                   6723:         $occurrences = &occurence_count($currquest,$matchon); 
                   6724:     }
                   6725:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6726:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6727:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6728:             my $bubble = substr($currquest,$ans,1);
                   6729:             if ($bubble =~ /$matchon/ ) {
                   6730:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6731:                     if ($bubble == 0) {
                   6732:                         $bubble = 10; 
                   6733:                     }
                   6734:                     $record->{"scantron.$ansnum.answer"} = 
                   6735:                         $alphabet->[$bubble-1];
                   6736:                 } else {
                   6737:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6738:                 }
                   6739:             } else {
                   6740:                 $record->{"scantron.$ansnum.answer"}='';
                   6741:             }
                   6742:             $ansnum++;
                   6743:         }
                   6744:     } elsif (!defined($currquest)
                   6745:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6746:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6747:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6748:             $record->{"scantron.$ansnum.answer"}='';
                   6749:             $ansnum++;
                   6750:         }
                   6751:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6752:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6753:         }
                   6754:     } else {
                   6755:         if ($$scantron_config{'Qon'} eq 'number') {
                   6756:             $currquest = &digits_to_letters($currquest);            
                   6757:         }
                   6758:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6759:             my $bubble = substr($currquest,$ans,1);
                   6760:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6761:             $ansnum++;
                   6762:         }
                   6763:     }
                   6764:     return $ansnum;
                   6765: }
1.447     foxr     6766: 
1.503     raeburn  6767: sub scantron_validator_positional {
                   6768:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6769:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6770:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6771: 
1.503     raeburn  6772:     # Otherwise there's a positional notation;
                   6773:     # each bubble line requires Qlength items, and there are filled in
                   6774:     # bubbles for each case where there 'Qon' characters.
                   6775:     #
1.447     foxr     6776: 
1.503     raeburn  6777:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6778: 
1.503     raeburn  6779:     # If the split only gives us one element.. the full length of the
                   6780:     # answer string, no bubbles are filled in:
1.447     foxr     6781: 
1.507     raeburn  6782:     if ($answers_needed eq '') {
                   6783:         return;
                   6784:     }
                   6785: 
1.503     raeburn  6786:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6787:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6788:             $record->{"scantron.$ansnum.answer"}='';
                   6789:             $ansnum++;
                   6790:         }
                   6791:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6792:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6793:         }
                   6794:     } elsif (scalar(@array) == 2) {
                   6795:         my $location = length($array[0]);
                   6796:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6797:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6798:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6799:             if ($ans eq $line_num) {
                   6800:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6801:             } else {
                   6802:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6803:             }
                   6804:             $ansnum++;
                   6805:          }
                   6806:     } else {
                   6807:         #  If there's more than one instance of a bubble character
                   6808:         #  That's a double bubble; with positional notation we can
                   6809:         #  record all the bubbles filled in as well as the
                   6810:         #  fact this response consists of multiple bubbles.
                   6811:         #
1.691     raeburn  6812:         my $responsenum = $questnum-1;
                   6813:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6814:             $responsenum = $respnumlookup->{$questnum-1}
                   6815:         }
                   6816:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6817:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6818:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6819:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6820:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6821:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6822:             my $doubleerror = 0;
                   6823:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6824:                    (!$doubleerror)) {
                   6825:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6826:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6827:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6828:                if (length(@currarray) > 2) {
                   6829:                    $doubleerror = 1;
                   6830:                } 
                   6831:             }
                   6832:             if ($doubleerror) {
                   6833:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6834:             }
                   6835:         } else {
                   6836:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6837:         }
                   6838:         my $item = $ansnum;
                   6839:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6840:             $record->{"scantron.$item.answer"} = '';
                   6841:             $item ++;
                   6842:         }
1.447     foxr     6843: 
1.503     raeburn  6844:         my @ans=@array;
                   6845:         my $i=0;
                   6846:         my $increment = 0;
                   6847:         while ($#ans) {
                   6848:             $i+=length($ans[0]) + $increment;
                   6849:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6850:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6851:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6852:             shift(@ans);
                   6853:             $increment = 1;
                   6854:         }
                   6855:         $ansnum += $answers_needed;
1.82      albertel 6856:     }
1.503     raeburn  6857:     return $ansnum;
1.82      albertel 6858: }
                   6859: 
1.423     albertel 6860: =pod
                   6861: 
                   6862: =item scantron_add_delay
                   6863: 
                   6864:    Adds an error message that occurred during the grading phase to a
                   6865:    queue of messages to be shown after grading pass is complete
                   6866: 
                   6867:  Arguments:
1.424     albertel 6868:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6869:    $scanline    - the scanline that caused the error
                   6870:    $errormesage - the error message
                   6871:    $errorcode   - a numeric code for the error
                   6872: 
                   6873:  Side Effects:
1.424     albertel 6874:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6875: 
                   6876: =cut
                   6877: 
1.82      albertel 6878: sub scantron_add_delay {
1.140     albertel 6879:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6880:     push(@$delayqueue,
                   6881: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6882: 	  'ecode' => $errorcode }
                   6883: 	 );
1.82      albertel 6884: }
                   6885: 
1.423     albertel 6886: =pod
                   6887: 
                   6888: =item scantron_find_student
                   6889: 
1.424     albertel 6890:    Finds the username for the current scanline
                   6891: 
                   6892:   Arguments:
                   6893:    $scantron_record - hash result from scantron_parse_scanline
                   6894:    $scan_data       - hash of correction information 
                   6895:                       (see &scantron_getfile() form more information)
                   6896:    $idmap           - hash from &username_to_idmap()
                   6897:    $line            - number of current scanline
                   6898:  
                   6899:   Returns:
                   6900:    Either 'username:domain' or undef if unknown
                   6901: 
1.423     albertel 6902: =cut
                   6903: 
1.82      albertel 6904: sub scantron_find_student {
1.157     albertel 6905:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6906:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6907:     if ($scanID =~ /^\s*$/) {
                   6908:  	return &scan_data($scan_data,"$line.user");
                   6909:     }
1.83      albertel 6910:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6911:  	if (lc($id) eq lc($scanID)) {
                   6912:  	    return $$idmap{$id};
                   6913:  	}
1.83      albertel 6914:     }
                   6915:     return undef;
                   6916: }
                   6917: 
1.423     albertel 6918: =pod
                   6919: 
                   6920: =item scantron_filter
                   6921: 
1.424     albertel 6922:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6923:    hidden resources was selected
                   6924: 
1.423     albertel 6925: =cut
                   6926: 
1.83      albertel 6927: sub scantron_filter {
                   6928:     my ($curres)=@_;
1.331     albertel 6929: 
                   6930:     if (ref($curres) && $curres->is_problem()) {
                   6931: 	# if the user has asked to not have either hidden
                   6932: 	# or 'randomout' controlled resources to be graded
                   6933: 	# don't include them
                   6934: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6935: 	    && $curres->randomout) {
                   6936: 	    return 0;
                   6937: 	}
1.83      albertel 6938: 	return 1;
                   6939:     }
                   6940:     return 0;
1.82      albertel 6941: }
                   6942: 
1.423     albertel 6943: =pod
                   6944: 
                   6945: =item scantron_process_corrections
                   6946: 
1.424     albertel 6947:    Gets correction information out of submitted form data and corrects
                   6948:    the scanline
                   6949: 
1.423     albertel 6950: =cut
                   6951: 
1.157     albertel 6952: sub scantron_process_corrections {
                   6953:     my ($r) = @_;
1.754     raeburn  6954:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6955:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6956:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6957:     my $which=$env{'form.scantron_line'};
1.200     albertel 6958:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6959:     my ($skip,$err,$errmsg);
1.257     albertel 6960:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6961: 	$skip=1;
1.257     albertel 6962:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6963: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6964: 	    $env{'form.scantron_domain'};
1.157     albertel 6965: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6966: 	($line,$err,$errmsg)=
                   6967: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6968: 				     'ID',{'newid'=>$newid,
1.257     albertel 6969: 				    'username'=>$env{'form.scantron_username'},
                   6970: 				    'domain'=>$env{'form.scantron_domain'}});
                   6971:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6972: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6973: 	my $newCODE;
1.192     albertel 6974: 	my %args;
1.190     albertel 6975: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6976: 	    $newCODE='use_unfound';
1.190     albertel 6977: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6978: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6979: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6980: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6981: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6982: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6983: 	}
1.257     albertel 6984: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6985: 	    $args{'CODE_ignore_dup'}=1;
                   6986: 	}
                   6987: 	$args{'CODE'}=$newCODE;
1.186     albertel 6988: 	($line,$err,$errmsg)=
                   6989: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6990: 				     'CODE',\%args);
1.257     albertel 6991:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6992: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6993: 	    ($line,$err,$errmsg)=
                   6994: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6995: 					 $which,'answer',
                   6996: 					 { 'question'=>$question,
1.503     raeburn  6997: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6998:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6999: 	    if ($err) { last; }
                   7000: 	}
                   7001:     }
                   7002:     if ($err) {
1.703     bisitz   7003:         $r->print(
                   7004:             '<p class="LC_error">'
                   7005:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   7006:                 $errmsg)
1.704     raeburn  7007:            .'</p>');
1.157     albertel 7008:     } else {
1.200     albertel 7009: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 7010: 	&scantron_putfile($scanlines,$scan_data);
                   7011:     }
                   7012: }
                   7013: 
1.423     albertel 7014: =pod
                   7015: 
                   7016: =item reset_skipping_status
                   7017: 
1.424     albertel 7018:    Forgets the current set of remember skipped scanlines (and thus
                   7019:    reverts back to considering all lines in the
                   7020:    scantron_skipped_<filename> file)
                   7021: 
1.423     albertel 7022: =cut
                   7023: 
1.200     albertel 7024: sub reset_skipping_status {
                   7025:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7026:     &scan_data($scan_data,'remember_skipping',undef,1);
                   7027:     &scantron_putfile(undef,$scan_data);
                   7028: }
                   7029: 
1.423     albertel 7030: =pod
                   7031: 
                   7032: =item start_skipping
                   7033: 
1.424     albertel 7034:    Marks a scanline to be skipped. 
                   7035: 
1.423     albertel 7036: =cut
                   7037: 
1.376     albertel 7038: sub start_skipping {
1.200     albertel 7039:     my ($scan_data,$i)=@_;
                   7040:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7041:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   7042: 	$remembered{$i}=2;
                   7043:     } else {
                   7044: 	$remembered{$i}=1;
                   7045:     }
1.200     albertel 7046:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   7047: }
                   7048: 
1.423     albertel 7049: =pod
                   7050: 
                   7051: =item should_be_skipped
                   7052: 
1.424     albertel 7053:    Checks whether a scanline should be skipped.
                   7054: 
1.423     albertel 7055: =cut
                   7056: 
1.200     albertel 7057: sub should_be_skipped {
1.376     albertel 7058:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 7059:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 7060: 	# not redoing old skips
1.376     albertel 7061: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 7062: 	return 0;
                   7063:     }
                   7064:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 7065: 
                   7066:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   7067: 	return 0;
                   7068:     }
1.200     albertel 7069:     return 1;
                   7070: }
                   7071: 
1.423     albertel 7072: =pod
                   7073: 
                   7074: =item remember_current_skipped
                   7075: 
1.424     albertel 7076:    Discovers what scanlines are in the scantron_skipped_<filename>
                   7077:    file and remembers them into scan_data for later use.
                   7078: 
1.423     albertel 7079: =cut
                   7080: 
1.200     albertel 7081: sub remember_current_skipped {
                   7082:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7083:     my %to_remember;
                   7084:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7085: 	if ($scanlines->{'skipped'}[$i]) {
                   7086: 	    $to_remember{$i}=1;
                   7087: 	}
                   7088:     }
1.376     albertel 7089: 
1.200     albertel 7090:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   7091:     &scantron_putfile(undef,$scan_data);
                   7092: }
                   7093: 
1.423     albertel 7094: =pod
                   7095: 
                   7096: =item check_for_error
                   7097: 
1.424     albertel 7098:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  7099:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 7100:     something went wrong.
                   7101: 
1.423     albertel 7102: =cut
                   7103: 
1.200     albertel 7104: sub check_for_error {
                   7105:     my ($r,$result)=@_;
                   7106:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 7107: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 7108:     }
                   7109: }
1.157     albertel 7110: 
1.423     albertel 7111: =pod
                   7112: 
                   7113: =item scantron_warning_screen
                   7114: 
1.424     albertel 7115:    Interstitial screen to make sure the operator has selected the
                   7116:    correct options before we start the validation phase.
                   7117: 
1.423     albertel 7118: =cut
                   7119: 
1.203     albertel 7120: sub scantron_warning_screen {
1.650     raeburn  7121:     my ($button_text,$symb)=@_;
1.257     albertel 7122:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  7123:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7124:     my $CODElist;
1.284     albertel 7125:     if ($scantron_config{'CODElocation'} &&
                   7126: 	$scantron_config{'CODEstart'} &&
                   7127: 	$scantron_config{'CODElength'}) {
                   7128: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   7129: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7130: 	$CODElist=
1.492     albertel 7131: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7132: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7133:     }
1.663     raeburn  7134:     my $lastbubblepoints;
                   7135:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7136:         $lastbubblepoints =
                   7137:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7138:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7139:     }
1.770     raeburn  7140:     return '
1.203     albertel 7141: <p>
1.492     albertel 7142: <span class="LC_warning">
1.705     raeburn  7143: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7144: </p>
                   7145: <table>
1.492     albertel 7146: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7147: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  7148: '.$CODElist.$lastbubblepoints.'
1.203     albertel 7149: </table>
1.680     raeburn  7150: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  7151: '.&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.770     raeburn  7152: ';
1.203     albertel 7153: }
                   7154: 
1.423     albertel 7155: =pod
                   7156: 
                   7157: =item scantron_do_warning
                   7158: 
1.424     albertel 7159:    Check if the operator has picked something for all required
                   7160:    fields. Error out if something is missing.
                   7161: 
1.423     albertel 7162: =cut
                   7163: 
1.203     albertel 7164: sub scantron_do_warning {
1.608     www      7165:     my ($r,$symb)=@_;
1.203     albertel 7166:     if (!$symb) {return '';}
1.324     albertel 7167:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7168:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7169:     if ( $env{'form.selectpage'} eq '' ||
                   7170: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7171: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7172: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7173: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7174: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7175: 	} 
1.257     albertel 7176: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7177: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.770     raeburn  7178: 	}
1.257     albertel 7179: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7180: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.770     raeburn  7181: 	}
1.237     albertel 7182:     } else {
1.650     raeburn  7183: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7184:         my ($checksec,@possibles) = &gradable_sections();
                   7185:         my $gradesections;
                   7186:         if ($checksec) {
                   7187:             my $file=$env{'form.scantron_selectfile'};
                   7188:             if (&valid_file($file)) {
                   7189:                 my %bysec = &scantron_get_sections();
                   7190:                 my $table;
                   7191:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7192:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7193:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7194:                              &Apache::loncommon::start_data_table_header_row().
                   7195:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7196:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7197:                     if ($bysec{'none'}) {
                   7198:                         $table .= &Apache::loncommon::start_data_table_row().
                   7199:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7200:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7201:                     }
                   7202:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7203:                         next if ($sec eq 'none');
                   7204:                         $table .= &Apache::loncommon::start_data_table_row().
                   7205:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7206:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7207:                     }
                   7208:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7209:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7210:                                       '<p>'.$table.'</p>';
                   7211:                     if (@possibles) {
                   7212:                         $gradesections .= '<p>'.
                   7213:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7214:                                               scalar(@possibles)).'<br />'.
                   7215:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7216:                                               '<i>'.$checksec.'</i>').' ';
                   7217:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7218:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7219:                         }
                   7220:                         $gradesections .= '</p>';
                   7221:                     }
                   7222:                 }
                   7223:             } else {
                   7224:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7225:             }
                   7226:         }
1.663     raeburn  7227:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7228: 	$r->print('
1.770     raeburn  7229: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7230: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7231: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7232: ');
1.237     albertel 7233:     }
1.614     www      7234:     $r->print("</form><br />");
1.203     albertel 7235:     return '';
                   7236: }
                   7237: 
1.423     albertel 7238: =pod
                   7239: 
                   7240: =item scantron_form_start
                   7241: 
1.424     albertel 7242:     html hidden input for remembering all selected grading options
                   7243: 
1.423     albertel 7244: =cut
                   7245: 
1.203     albertel 7246: sub scantron_form_start {
                   7247:     my ($max_bubble)=@_;
                   7248:     my $result= <<SCANTRONFORM;
                   7249: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7250:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7251:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7252:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7253:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7254:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7255:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7256:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7257:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7258:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7259: SCANTRONFORM
1.447     foxr     7260: 
                   7261:   my $line = 0;
                   7262:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7263:        my $chunk =
                   7264: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7265:        $chunk .=
                   7266: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7267:        $chunk .= 
                   7268:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7269:        $chunk .=
                   7270:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7271:        $chunk .=
                   7272:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7273:        $result .= $chunk;
                   7274:        $line++;
1.691     raeburn  7275:     }
1.203     albertel 7276:     return $result;
                   7277: }
                   7278: 
1.423     albertel 7279: =pod
                   7280: 
                   7281: =item scantron_validate_file
                   7282: 
1.659     raeburn  7283:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7284: 
                   7285:     Also processes any necessary information resets that need to
                   7286:     occur before validation begins (ignore previous corrections,
                   7287:     restarting the skipped records processing)
                   7288: 
1.423     albertel 7289: =cut
                   7290: 
1.157     albertel 7291: sub scantron_validate_file {
1.608     www      7292:     my ($r,$symb) = @_;
1.157     albertel 7293:     if (!$symb) {return '';}
1.324     albertel 7294:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7295:     
1.703     bisitz   7296:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7297:     # them when doing the corrections reset
1.257     albertel 7298:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7299: 	&reset_skipping_status();
                   7300:     }
1.257     albertel 7301:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7302: 	&remember_current_skipped();
1.257     albertel 7303: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7304:     }
                   7305: 
1.257     albertel 7306:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7307: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7308: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7309: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7310: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7311:     }
1.200     albertel 7312: 
1.257     albertel 7313:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7314: 	&scantron_process_corrections($r);
                   7315:     }
1.770     raeburn  7316: 
                   7317:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7318:     my ($checksec,@gradable);
                   7319:     if ($env{'request.course.sec'}) {
                   7320:         ($checksec,my @possibles) = &gradable_sections();
                   7321:         if ($checksec) {
                   7322:             if (@possibles) {
                   7323:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7324:                 if (@chosensecs) {
                   7325:                     foreach my $sec (@chosensecs) {
                   7326:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7327:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7328:                                 push(@gradable,$sec);
                   7329:                             }
                   7330:                         }
                   7331:                     }
                   7332:                 }
                   7333:             }
                   7334:             $r->print('<p><table>');
                   7335:             if (@gradable) {
                   7336:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7337:                 $r->print(
                   7338:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7339:             } else {
                   7340:                 $r->print(
                   7341:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7342:             }
                   7343:             $r->print('</table></p>');
                   7344:         }
                   7345:     }
                   7346:     $r->rflush();
                   7347: 
1.157     albertel 7348:     #get the student pick code ready
                   7349:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7350:     my $nav_error;
1.754     raeburn  7351:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7352:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7353:     if ($nav_error) {
                   7354:         $r->print(&navmap_errormsg());
                   7355:         return '';
                   7356:     }
1.203     albertel 7357:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7358:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7359:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7360:     }
1.157     albertel 7361:     $r->print($result);
                   7362:     
1.334     albertel 7363:     my @validate_phases=( 'sequence',
                   7364: 			  'ID',
1.157     albertel 7365: 			  'CODE',
                   7366: 			  'doublebubble',
                   7367: 			  'missingbubbles');
1.257     albertel 7368:     if (!$env{'form.validatepass'}) {
                   7369: 	$env{'form.validatepass'} = 0;
1.157     albertel 7370:     }
1.257     albertel 7371:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7372:     my %skipbysec=();
1.448     foxr     7373: 
1.157     albertel 7374:     my $stop=0;
                   7375:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7376: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7377: 	$r->rflush();
1.691     raeburn  7378:      
1.157     albertel 7379: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7380: 	{
                   7381: 	    no strict 'refs';
1.770     raeburn  7382:             my @extras=();
                   7383:             if ($validate_phases[$currentphase] eq 'ID') {
                   7384:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7385:             }
                   7386: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7387: 	}
                   7388:     }
                   7389:     if (!$stop) {
1.650     raeburn  7390: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7391:         my $secinfo;
                   7392:         if (keys(%skipbysec) > 0) {
                   7393:             my $seclist = '<ul>';
                   7394:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7395:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7396:             }
                   7397:             $seclist .= '</ul>';
                   7398:             $secinfo = '<p class="LC_info">'.
                   7399:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7400:                            $seclist).
                   7401:                        '</p>';
                   7402:         }
1.542     raeburn  7403: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7404:                   $secinfo.$warning.
1.542     raeburn  7405:                   &mt('Perform verification for each student after storage of submissions?').
                   7406:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7407:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7408:                   ('&nbsp;'x3).'<label>'.
                   7409:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7410:                   '</label></span><br />'.
                   7411:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7412:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7413:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7414:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7415:     } else {
                   7416: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7417: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7418:     }
                   7419:     if ($stop) {
1.334     albertel 7420: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7421: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7422: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7423: 
1.650     raeburn  7424: 	    $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 7425: 	} else {
1.503     raeburn  7426:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7427: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7428:             } else {
1.539     riegler  7429:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7430:             }
1.492     albertel 7431: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7432: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7433: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7434: 	}
1.157     albertel 7435:     }
1.614     www      7436:     $r->print(" </form><br />");
1.157     albertel 7437:     return '';
                   7438: }
                   7439: 
1.423     albertel 7440: 
                   7441: =pod
                   7442: 
                   7443: =item scantron_remove_file
                   7444: 
1.659     raeburn  7445:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7446:    scantron_original_<filename> is never removed
                   7447: 
                   7448: 
1.423     albertel 7449: =cut
                   7450: 
1.200     albertel 7451: sub scantron_remove_file {
1.192     albertel 7452:     my ($which)=@_;
1.257     albertel 7453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7455:     my $file='scantron_';
1.200     albertel 7456:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7457: 	$file.=$which.'_';
1.192     albertel 7458:     } else {
                   7459: 	return 'refused';
                   7460:     }
1.257     albertel 7461:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7462:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7463: }
                   7464: 
1.423     albertel 7465: 
                   7466: =pod
                   7467: 
                   7468: =item scantron_remove_scan_data
                   7469: 
1.659     raeburn  7470:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7471:    data file.  (In the case that both the are doing skipped records we need
                   7472:    to remember the old skipped lines for the time being so that element
                   7473:    persists for a while.)
                   7474: 
1.423     albertel 7475: =cut
                   7476: 
1.200     albertel 7477: sub scantron_remove_scan_data {
1.257     albertel 7478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7480:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7481:     my @todelete;
1.257     albertel 7482:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7483:     foreach my $key (@keys) {
                   7484: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7485: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7486: 		$key=~/remember_skipping/) {
                   7487: 		next;
                   7488: 	    }
1.192     albertel 7489: 	    push(@todelete,$key);
                   7490: 	}
                   7491:     }
1.200     albertel 7492:     my $result;
1.192     albertel 7493:     if (@todelete) {
1.491     albertel 7494: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7495: 				       \@todelete,$cdom,$cname);
                   7496:     } else {
                   7497: 	$result = 'ok';
1.192     albertel 7498:     }
                   7499:     return $result;
                   7500: }
                   7501: 
1.423     albertel 7502: 
                   7503: =pod
                   7504: 
                   7505: =item scantron_getfile
                   7506: 
1.659     raeburn  7507:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7508:     the scan_data hash
                   7509:   
                   7510:   Arguments:
                   7511:     None
                   7512: 
                   7513:   Returns:
                   7514:     2 hash references
                   7515: 
                   7516:      - first one has 
                   7517:          orig      -
                   7518:          corrected -
                   7519:          skipped   -  each of which points to an array ref of the specified
                   7520:                       file broken up into individual lines
                   7521:          count     - number of scanlines
                   7522:  
                   7523:      - second is the scan_data hash possible keys are
1.425     albertel 7524:        ($number refers to scanline numbered $number and thus the key affects
                   7525:         only that scanline
                   7526:         $bubline refers to the specific bubble line element and the aspects
                   7527:         refers to that specific bubble line element)
                   7528: 
                   7529:        $number.user - username:domain to use
                   7530:        $number.CODE_ignore_dup 
                   7531:                     - ignore the duplicate CODE error 
                   7532:        $number.useCODE
                   7533:                     - use the CODE in the scanline as is
                   7534:        $number.no_bubble.$bubline
                   7535:                     - it is valid that there is no bubbled in bubble
                   7536:                       at $number $bubline
                   7537:        remember_skipping
                   7538:                     - a frozen hash containing keys of $number and values
                   7539:                       of either 
                   7540:                         1 - we are on a 'do skipped records pass' and plan
                   7541:                             on processing this line
                   7542:                         2 - we are on a 'do skipped records pass' and this
                   7543:                             scanline has been marked to skip yet again
1.424     albertel 7544: 
1.423     albertel 7545: =cut
                   7546: 
1.157     albertel 7547: sub scantron_getfile {
1.200     albertel 7548:     #FIXME really would prefer a scantron directory
1.257     albertel 7549:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7550:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7551:     my $lines;
                   7552:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7553: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7554:     my %scanlines;
                   7555:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7556:     my $temp=$scanlines{'orig'};
                   7557:     $scanlines{'count'}=$#$temp;
                   7558: 
                   7559:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7560: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7561:     if ($lines eq '-1') {
                   7562: 	$scanlines{'corrected'}=[];
                   7563:     } else {
                   7564: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7565:     }
                   7566:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7567: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7568:     if ($lines eq '-1') {
                   7569: 	$scanlines{'skipped'}=[];
                   7570:     } else {
                   7571: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7572:     }
1.175     albertel 7573:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7574:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7575:     my %scan_data = @tmp;
                   7576:     return (\%scanlines,\%scan_data);
                   7577: }
                   7578: 
1.423     albertel 7579: =pod
                   7580: 
                   7581: =item lonnet_putfile
                   7582: 
1.424     albertel 7583:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7584: 
                   7585:  Arguments:
                   7586:    $contents - data to store
                   7587:    $filename - filename to store $contents into
                   7588: 
                   7589:  Returns:
                   7590:    result value from &Apache::lonnet::finishuserfileupload
                   7591: 
1.423     albertel 7592: =cut
                   7593: 
1.157     albertel 7594: sub lonnet_putfile {
                   7595:     my ($contents,$filename)=@_;
1.257     albertel 7596:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7597:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7598:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7599:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7600: 
                   7601: }
                   7602: 
1.423     albertel 7603: =pod
                   7604: 
                   7605: =item scantron_putfile
                   7606: 
1.659     raeburn  7607:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7608:     scan_data hash. (Does not modify the original version only the
                   7609:     corrected and skipped versions.
                   7610: 
                   7611:  Arguments:
                   7612:     $scanlines - hash ref that looks like the first return value from
                   7613:                  &scantron_getfile()
                   7614:     $scan_data - hash ref that looks like the second return value from
                   7615:                  &scantron_getfile()
                   7616: 
1.423     albertel 7617: =cut
                   7618: 
1.157     albertel 7619: sub scantron_putfile {
                   7620:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7621:     #FIXME really would prefer a scantron directory
1.257     albertel 7622:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7623:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7624:     if ($scanlines) {
                   7625: 	my $prefix='scantron_';
1.157     albertel 7626: # no need to update orig, shouldn't change
                   7627: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7628: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7629: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7630: 			$prefix.'corrected_'.
1.257     albertel 7631: 			$env{'form.scantron_selectfile'});
1.200     albertel 7632: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7633: 			$prefix.'skipped_'.
1.257     albertel 7634: 			$env{'form.scantron_selectfile'});
1.200     albertel 7635:     }
1.175     albertel 7636:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7637: }
                   7638: 
1.423     albertel 7639: =pod
                   7640: 
                   7641: =item scantron_get_line
                   7642: 
1.424     albertel 7643:    Returns the correct version of the scanline
                   7644: 
                   7645:  Arguments:
                   7646:     $scanlines - hash ref that looks like the first return value from
                   7647:                  &scantron_getfile()
                   7648:     $scan_data - hash ref that looks like the second return value from
                   7649:                  &scantron_getfile()
                   7650:     $i         - number of the requested line (starts at 0)
                   7651: 
                   7652:  Returns:
                   7653:    A scanline, (either the original or the corrected one if it
                   7654:    exists), or undef if the requested scanline should be
                   7655:    skipped. (Either because it's an skipped scanline, or it's an
                   7656:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7657:    pass.
                   7658: 
1.423     albertel 7659: =cut
                   7660: 
1.157     albertel 7661: sub scantron_get_line {
1.200     albertel 7662:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7663:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7664:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7665:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7666:     return $scanlines->{'orig'}[$i]; 
                   7667: }
                   7668: 
1.423     albertel 7669: =pod
                   7670: 
                   7671: =item scantron_todo_count
                   7672: 
1.424     albertel 7673:     Counts the number of scanlines that need processing.
                   7674: 
                   7675:  Arguments:
                   7676:     $scanlines - hash ref that looks like the first return value from
                   7677:                  &scantron_getfile()
                   7678:     $scan_data - hash ref that looks like the second return value from
                   7679:                  &scantron_getfile()
                   7680: 
                   7681:  Returns:
                   7682:     $count - number of scanlines to process
                   7683: 
1.423     albertel 7684: =cut
                   7685: 
1.200     albertel 7686: sub get_todo_count {
                   7687:     my ($scanlines,$scan_data)=@_;
                   7688:     my $count=0;
                   7689:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7690: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7691: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7692: 	$count++;
                   7693:     }
                   7694:     return $count;
                   7695: }
                   7696: 
1.423     albertel 7697: =pod
                   7698: 
                   7699: =item scantron_put_line
                   7700: 
1.659     raeburn  7701:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7702:     data file.
                   7703: 
                   7704:  Arguments:
                   7705:     $scanlines - hash ref that looks like the first return value from
                   7706:                  &scantron_getfile()
                   7707:     $scan_data - hash ref that looks like the second return value from
                   7708:                  &scantron_getfile()
                   7709:     $i         - line number to update
                   7710:     $newline   - contents of the updated scanline
                   7711:     $skip      - if true make the line for skipping and update the
                   7712:                  'skipped' file
                   7713: 
1.423     albertel 7714: =cut
                   7715: 
1.157     albertel 7716: sub scantron_put_line {
1.200     albertel 7717:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7718:     if ($skip) {
                   7719: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7720: 	&start_skipping($scan_data,$i);
1.157     albertel 7721: 	return;
                   7722:     }
                   7723:     $scanlines->{'corrected'}[$i]=$newline;
                   7724: }
                   7725: 
1.423     albertel 7726: =pod
                   7727: 
                   7728: =item scantron_clear_skip
                   7729: 
1.424     albertel 7730:    Remove a line from the 'skipped' file
                   7731: 
                   7732:  Arguments:
                   7733:     $scanlines - hash ref that looks like the first return value from
                   7734:                  &scantron_getfile()
                   7735:     $scan_data - hash ref that looks like the second return value from
                   7736:                  &scantron_getfile()
                   7737:     $i         - line number to update
                   7738: 
1.423     albertel 7739: =cut
                   7740: 
1.376     albertel 7741: sub scantron_clear_skip {
                   7742:     my ($scanlines,$scan_data,$i)=@_;
                   7743:     if (exists($scanlines->{'skipped'}[$i])) {
                   7744: 	undef($scanlines->{'skipped'}[$i]);
                   7745: 	return 1;
                   7746:     }
                   7747:     return 0;
                   7748: }
                   7749: 
1.423     albertel 7750: =pod
                   7751: 
                   7752: =item scantron_filter_not_exam
                   7753: 
1.424     albertel 7754:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7755:    filter out resources that are not marked as 'exam' mode
                   7756: 
1.423     albertel 7757: =cut
                   7758: 
1.334     albertel 7759: sub scantron_filter_not_exam {
                   7760:     my ($curres)=@_;
                   7761:     
                   7762:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7763: 	# if the user has asked to not have either hidden
                   7764: 	# or 'randomout' controlled resources to be graded
                   7765: 	# don't include them
                   7766: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7767: 	    && $curres->randomout) {
                   7768: 	    return 0;
                   7769: 	}
                   7770: 	return 1;
                   7771:     }
                   7772:     return 0;
                   7773: }
                   7774: 
1.423     albertel 7775: =pod
                   7776: 
                   7777: =item scantron_validate_sequence
                   7778: 
1.424     albertel 7779:     Validates the selected sequence, checking for resource that are
                   7780:     not set to exam mode.
                   7781: 
1.423     albertel 7782: =cut
                   7783: 
1.334     albertel 7784: sub scantron_validate_sequence {
                   7785:     my ($r,$currentphase) = @_;
                   7786: 
                   7787:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7788:     unless (ref($navmap)) {
                   7789:         $r->print(&navmap_errormsg());
                   7790:         return (1,$currentphase);
                   7791:     }
1.334     albertel 7792:     my (undef,undef,$sequence)=
                   7793: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7794: 
                   7795:     my $map=$navmap->getResourceByUrl($sequence);
                   7796: 
                   7797:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7798:                                     value="ignore" />');
                   7799:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7800: 	my @resources=
                   7801: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7802: 	if (@resources) {
1.675     bisitz   7803: 	    $r->print(
                   7804:                 '<p class="LC_warning">'
                   7805:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7806:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7807:                    .' work correctly.')
                   7808:                .'</p>'
                   7809:             );
1.334     albertel 7810: 	    return (1,$currentphase);
                   7811: 	}
                   7812:     }
                   7813: 
                   7814:     return (0,$currentphase+1);
                   7815: }
                   7816: 
1.423     albertel 7817: 
                   7818: 
1.157     albertel 7819: sub scantron_validate_ID {
1.770     raeburn  7820:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7821:     
                   7822:     #get student info
                   7823:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7824:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7825:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7826: 
                   7827:     #get scantron line setup
1.754     raeburn  7828:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7829:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7830: 
                   7831:     my $nav_error;
1.649     raeburn  7832:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7833:     if ($nav_error) {
                   7834:         $r->print(&navmap_errormsg());
                   7835:         return(1,$currentphase);
                   7836:     }
1.157     albertel 7837: 
                   7838:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7839:     my $unsavedskips = 0;
1.157     albertel 7840:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7841: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7842: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7843: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7844: 						 $scan_data);
                   7845: 	my $id=$$scan_record{'scantron.ID'};
                   7846: 	my $found;
                   7847: 	foreach my $checkid (keys(%idmap)) {
                   7848: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7849: 	}
                   7850: 	if ($found) {
                   7851: 	    my $username=$idmap{$found};
1.770     raeburn  7852:             if ($checksec) {
                   7853:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7854:                     my $stusec = $classlist->{$username}->[$secidx];
                   7855:                     if ($stusec ne $checksec) {
                   7856:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7857:                             my $skip=1;
                   7858:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7859:                             if (ref($skipbysec) eq 'HASH') {
                   7860:                                 if ($stusec eq '') {
                   7861:                                     $skipbysec->{'none'} ++;
                   7862:                                 } else {
                   7863:                                     $skipbysec->{$stusec} ++;
                   7864:                                 }
                   7865:                             }
                   7866:                             $unsavedskips ++;
                   7867:                             next;
                   7868:                         }
                   7869:                     }
                   7870:                 }
                   7871:             }
1.157     albertel 7872: 	    if ($found{'ids'}{$found}) {
                   7873: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7874: 					 $line,'duplicateID',$found);
1.770     raeburn  7875:                 if ($unsavedskips) {
                   7876:                     &scantron_putfile($scanlines,$scan_data);
                   7877:                     $unsavedskips = 0;
                   7878:                 }
1.194     albertel 7879: 		return(1,$currentphase);
1.157     albertel 7880: 	    } elsif ($found{'usernames'}{$username}) {
                   7881: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7882: 					 $line,'duplicateID',$username);
1.770     raeburn  7883:                 if ($unsavedskips) {
                   7884:                     &scantron_putfile($scanlines,$scan_data);
                   7885:                     $unsavedskips = 0;
                   7886:                 }
1.194     albertel 7887: 		return(1,$currentphase);
1.157     albertel 7888: 	    }
1.186     albertel 7889: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7890: 	    $found{'ids'}{$found}++;
                   7891: 	    $found{'usernames'}{$username}++;
                   7892: 	} else {
                   7893: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7894: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7895:                 if (($checksec && $username ne '')) {
                   7896:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7897:                         my $stusec = $classlist->{$username}->[$secidx];
                   7898:                         if ($stusec ne $checksec) {
                   7899:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7900:                                 my $skip=1;
                   7901:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7902:                                 if (ref($skipbysec) eq 'HASH') {
                   7903:                                     if ($stusec eq '') {
                   7904:                                         $skipbysec->{'none'} ++;
                   7905:                                     } else {
                   7906:                                         $skipbysec->{$stusec} ++;
                   7907:                                     }
                   7908:                                 }
                   7909:                                 $unsavedskips ++;
                   7910:                                 next;
                   7911:                             }
                   7912:                         }
                   7913:                     }
                   7914: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7915: 		    &scantron_get_correction($r,$i,$scan_record,
                   7916: 					     \%scantron_config,
                   7917: 					     $line,'duplicateID',$username);
1.770     raeburn  7918:                     if ($unsavedskips) {
                   7919:                         &scantron_putfile($scanlines,$scan_data);
                   7920:                         $unsavedskips = 0;
                   7921:                     }
1.194     albertel 7922: 		    return(1,$currentphase);
1.157     albertel 7923: 		} elsif (!defined($username)) {
                   7924: 		    &scantron_get_correction($r,$i,$scan_record,
                   7925: 					     \%scantron_config,
                   7926: 					     $line,'incorrectID');
1.770     raeburn  7927:                     if ($unsavedskips) {
                   7928:                         &scantron_putfile($scanlines,$scan_data);
                   7929:                         $unsavedskips = 0;
                   7930:                     }
1.194     albertel 7931: 		    return(1,$currentphase);
1.157     albertel 7932: 		}
                   7933: 		$found{'usernames'}{$username}++;
                   7934: 	    } else {
                   7935: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7936: 					 $line,'incorrectID');
1.770     raeburn  7937:                 if ($unsavedskips) {
                   7938:                     &scantron_putfile($scanlines,$scan_data);
                   7939:                     $unsavedskips = 0;
                   7940:                 }
1.194     albertel 7941: 		return(1,$currentphase);
1.157     albertel 7942: 	    }
                   7943: 	}
                   7944:     }
1.770     raeburn  7945:     if ($unsavedskips) {
                   7946:         &scantron_putfile($scanlines,$scan_data);
                   7947:         $unsavedskips = 0;
                   7948:     }
1.157     albertel 7949:     return (0,$currentphase+1);
                   7950: }
                   7951: 
1.770     raeburn  7952: sub scantron_get_sections {
                   7953:     my %bysec;
                   7954:     if ($env{'form.scantron_format'} ne '') {
                   7955:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   7956:         my ($scanlines,$scan_data)=&scantron_getfile();
                   7957:         my $classlist=&Apache::loncoursedata::get_classlist();
                   7958:         my %idmap=&username_to_idmap($classlist);
                   7959:         foreach my $key (keys(%idmap)) {
                   7960:             my $lckey = lc($key);
                   7961:             $idmap{$lckey} = $idmap{$key};
                   7962:         }
                   7963:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   7964:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7965:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7966:             if ($line=~/^[\s\cz]*$/) { next; }
                   7967:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7968:                                                      $scan_data);
                   7969:             my $id=lc($$scan_record{'scantron.ID'});
                   7970:             if (exists($idmap{$id})) {
                   7971:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   7972:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   7973:                     if ($stusec eq '') {
                   7974:                         $bysec{'none'} ++;
                   7975:                     } else {
                   7976:                         $bysec{$stusec} ++;
                   7977:                     }
                   7978:                 }
                   7979:             }
                   7980:         }
                   7981:     }
                   7982:     return %bysec;
                   7983: }
1.423     albertel 7984: 
1.157     albertel 7985: sub scantron_get_correction {
1.691     raeburn  7986:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7987:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7988: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7989: #to show both the current line and the previous one and allow skipping
                   7990: #the previous one or the current one
                   7991: 
1.333     albertel 7992:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7993:         $r->print(
                   7994:             '<p class="LC_warning">'
                   7995:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7996:                 "<b>$error</b>",
                   7997:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7998:            ."</p> \n");
1.157     albertel 7999:     } else {
1.658     bisitz   8000:         $r->print(
                   8001:             '<p class="LC_warning">'
                   8002:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   8003:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   8004:            ."</p> \n");
                   8005:     }
                   8006:     my $message =
                   8007:         '<p>'
                   8008:        .&mt('The ID on the form is [_1]',
                   8009:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   8010:        .'<br />'
1.665     raeburn  8011:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   8012:             $$scan_record{'scantron.LastName'},
                   8013:             $$scan_record{'scantron.FirstName'})
                   8014:        .'</p>';
1.242     albertel 8015: 
1.157     albertel 8016:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   8017:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  8018:                            # Array populated for doublebubble or
                   8019:     my @lines_to_correct;  # missingbubble errors to build javascript
                   8020:                            # to validate radio button checking   
                   8021: 
1.157     albertel 8022:     if ($error =~ /ID$/) {
1.186     albertel 8023: 	if ($error eq 'incorrectID') {
1.658     bisitz   8024:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 8025: 		      "</p>\n");
1.157     albertel 8026: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   8027:             $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 8028: 	}
1.242     albertel 8029: 	$r->print($message);
1.492     albertel 8030: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 8031: 	$r->print("\n<ul><li> ");
                   8032: 	#FIXME it would be nice if this sent back the user ID and
                   8033: 	#could do partial userID matches
                   8034: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   8035: 				       'scantron_username','scantron_domain'));
                   8036: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   8037: 	$r->print("\n:\n".
1.257     albertel 8038: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 8039: 
                   8040: 	$r->print('</li>');
1.186     albertel 8041:     } elsif ($error =~ /CODE$/) {
                   8042: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   8043: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 8044: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   8045: 	    $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 8046: 	}
1.658     bisitz   8047: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   8048: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   8049:                  ."</p>\n");
1.242     albertel 8050: 	$r->print($message);
1.658     bisitz   8051: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 8052: 	$r->print("\n<br /> ");
1.194     albertel 8053: 	my $i=0;
1.273     albertel 8054: 	if ($error eq 'incorrectCODE' 
                   8055: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 8056: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 8057: 	    if ($closest > 0) {
                   8058: 		foreach my $testcode (@{$closest}) {
                   8059: 		    my $checked='';
1.569     bisitz   8060: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8061: 		    $r->print("
                   8062:    <label>
1.569     bisitz   8063:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 8064:        ".&mt("Use the similar CODE [_1] instead.",
                   8065: 	    "<b><tt>".$testcode."</tt></b>")."
                   8066:     </label>
                   8067:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 8068: 		    $r->print("\n<br />");
                   8069: 		    $i++;
                   8070: 		}
1.194     albertel 8071: 	    }
                   8072: 	}
1.273     albertel 8073: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   8074: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 8075: 	    $r->print("
                   8076:     <label>
1.569     bisitz   8077:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  8078:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 8079: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   8080:     </label>");
1.273     albertel 8081: 	    $r->print("\n<br />");
                   8082: 	}
1.194     albertel 8083: 
1.597     wenzelju 8084: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 8085: function change_radio(field) {
1.190     albertel 8086:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 8087:     var i;
                   8088:     for (i=0;i<slct.length;i++) {
                   8089:         if (slct[i].value==field) { slct[i].checked=true; }
                   8090:     }
                   8091: }
                   8092: ENDSCRIPT
1.187     albertel 8093: 	my $href="/adm/pickcode?".
1.359     www      8094: 	   "form=".&escape("scantronupload").
                   8095: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   8096: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   8097: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   8098: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 8099: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 8100: 	    $r->print("
                   8101:     <label>
                   8102:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   8103:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   8104: 	     "<a target='_blank' href='$href'>","</a>")."
                   8105:     </label> 
1.558     bisitz   8106:     ".&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 8107: 	    $r->print("\n<br />");
                   8108: 	}
1.492     albertel 8109: 	$r->print("
                   8110:     <label>
                   8111:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   8112:        ".&mt("Use [_1] as the CODE.",
                   8113: 	     "</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 8114: 	$r->print("\n<br /><br />");
1.157     albertel 8115:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   8116: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     8117: 
                   8118: 	# The form field scantron_questions is acutally a list of line numbers.
                   8119: 	# represented by this form so:
                   8120: 
1.691     raeburn  8121: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8122:                                                 $respnumlookup,$startline);
1.497     foxr     8123: 
1.157     albertel 8124: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8125: 		  $line_list.'" />');
1.242     albertel 8126: 	$r->print($message);
1.492     albertel 8127: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 8128: 	foreach my $question (@{$arg}) {
1.503     raeburn  8129: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8130:                                                    $scan_record, $error,
                   8131:                                                    $randomorder,$randompick,
                   8132:                                                    $respnumlookup,$startline);
1.524     raeburn  8133:             push(@lines_to_correct,@linenums);
1.157     albertel 8134: 	}
1.503     raeburn  8135:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8136:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   8137: 	$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 8138: 	$r->print($message);
1.492     albertel 8139: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  8140: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     8141: 
1.503     raeburn  8142: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     8143: 	# a list of question numbers. Therefore:
                   8144: 	#
1.691     raeburn  8145: 
                   8146: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   8147:                                                 $respnumlookup,$startline);
1.497     foxr     8148: 
1.157     albertel 8149: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     8150: 		  $line_list.'" />');
1.157     albertel 8151: 	foreach my $question (@{$arg}) {
1.503     raeburn  8152: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  8153:                                                    $scan_record, $error,
                   8154:                                                    $randomorder,$randompick,
                   8155:                                                    $respnumlookup,$startline);
1.524     raeburn  8156:             push(@lines_to_correct,@linenums);
1.157     albertel 8157: 	}
1.503     raeburn  8158:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8159:     } else {
                   8160: 	$r->print("\n<ul>");
                   8161:     }
                   8162:     $r->print("\n</li></ul>");
1.497     foxr     8163: }
                   8164: 
1.503     raeburn  8165: sub verify_bubbles_checked {
                   8166:     my (@ansnums) = @_;
                   8167:     my $ansnumstr = join('","',@ansnums);
                   8168:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8169:     &js_escape(\$warning);
1.767     raeburn  8170:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8171: function verify_bubble_radio(form) {
                   8172:     var ansnumArray = new Array ("$ansnumstr");
                   8173:     var need_bubble_count = 0;
                   8174:     for (var i=0; i<ansnumArray.length; i++) {
                   8175:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8176:             var bubble_picked = 0; 
                   8177:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8178:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8179:                     bubble_picked = 1;
                   8180:                 }
                   8181:             }
                   8182:             if (bubble_picked == 0) {
                   8183:                 need_bubble_count ++;
                   8184:             }
                   8185:         }
                   8186:     }
                   8187:     if (need_bubble_count) {
                   8188:         alert("$warning");
                   8189:         return;
                   8190:     }
                   8191:     form.submit(); 
                   8192: }
                   8193: ENDSCRIPT
                   8194:     return $output;
                   8195: }
                   8196: 
1.497     foxr     8197: =pod
                   8198: 
                   8199: =item  questions_to_line_list
1.157     albertel 8200: 
1.497     foxr     8201: Converts a list of questions into a string of comma separated
                   8202: line numbers in the answer sheet used by the questions.  This is
                   8203: used to fill in the scantron_questions form field.
                   8204: 
                   8205:   Arguments:
                   8206:      questions    - Reference to an array of questions.
1.691     raeburn  8207:      randomorder  - True if randomorder in use.
                   8208:      randompick   - True if randompick in use.
                   8209:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8210:                      for current line to question number used for same question
                   8211:                      in "Master Seqence" (as seen by Course Coordinator).
                   8212:      startline    - Reference to hash where key is question number (0 is first)
                   8213:                     and key is number of first bubble line for current student
                   8214:                     or code-based randompick and/or randomorder.
1.693     raeburn  8215: 
1.497     foxr     8216: =cut
                   8217: 
                   8218: 
                   8219: sub questions_to_line_list {
1.691     raeburn  8220:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8221:     my @lines;
                   8222: 
1.503     raeburn  8223:     foreach my $item (@{$questions}) {
                   8224:         my $question = $item;
                   8225:         my ($first,$count,$last);
                   8226:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8227:             $question = $1;
                   8228:             my $subquestion = $2;
1.691     raeburn  8229:             my $responsenum = $question-1;
                   8230:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8231:                 $responsenum = $respnumlookup->{$question-1};
                   8232:                 if (ref($startline) eq 'HASH') {
                   8233:                     $first = $startline->{$question-1} + 1;
                   8234:                 }
                   8235:             } else {
                   8236:                 $first = $first_bubble_line{$responsenum} + 1;
                   8237:             }
                   8238:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8239:             my $subcount = 1;
                   8240:             while ($subcount<$subquestion) {
                   8241:                 $first += $subans[$subcount-1];
                   8242:                 $subcount ++;
                   8243:             }
                   8244:             $count = $subans[$subquestion-1];
                   8245:         } else {
1.691     raeburn  8246:             my $responsenum = $question-1;
                   8247:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8248:                 $responsenum = $respnumlookup->{$question-1};
                   8249:                 if (ref($startline) eq 'HASH') {
                   8250:                     $first = $startline->{$question-1} + 1;
                   8251:                 }
                   8252:             } else {
                   8253:                 $first = $first_bubble_line{$responsenum} + 1;
                   8254:             }
                   8255: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8256:         }
1.506     raeburn  8257:         $last = $first+$count-1;
1.503     raeburn  8258:         push(@lines, ($first..$last));
1.497     foxr     8259:     }
                   8260:     return join(',', @lines);
                   8261: }
                   8262: 
                   8263: =pod 
                   8264: 
                   8265: =item prompt_for_corrections
                   8266: 
                   8267: Prompts for a potentially multiline correction to the
                   8268: user's bubbling (factors out common code from scantron_get_correction
                   8269: for multi and missing bubble cases).
                   8270: 
                   8271:  Arguments:
                   8272:    $r           - Apache request object.
                   8273:    $question    - The question number to prompt for.
                   8274:    $scan_config - The scantron file configuration hash.
                   8275:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8276:    $error       - Type of error
1.691     raeburn  8277:    $randomorder - True if randomorder in use.
                   8278:    $randompick  - True if randompick in use.
                   8279:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8280:                     for current line to question number used for same question
                   8281:                     in "Master Seqence" (as seen by Course Coordinator).
                   8282:    $startline   - Reference to hash where key is question number (0 is first)
                   8283:                   and value is number of first bubble line for current student
                   8284:                   or code-based randompick and/or randomorder.
                   8285: 
1.497     foxr     8286: 
                   8287:  Implicit inputs:
                   8288:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8289:                                   Numbered from 0 (but question numbers are from
                   8290:                                   1.
                   8291:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8292:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8293:                                   type problems render as separate sub-questions, 
1.503     raeburn  8294:                                   in exam mode. This hash contains a 
                   8295:                                   comma-separated list of the lines per 
                   8296:                                   sub-question.
1.510     raeburn  8297:    %responsetype_per_response   - essayresponse, formularesponse,
                   8298:                                   stringresponse, imageresponse, reactionresponse,
                   8299:                                   and organicresponse type problem parts can have
1.503     raeburn  8300:                                   multiple lines per response if the weight
                   8301:                                   assigned exceeds 10.  In this case, only
                   8302:                                   one bubble per line is permitted, but more 
                   8303:                                   than one line might contain bubbles, e.g.
                   8304:                                   bubbling of: line 1 - J, line 2 - J, 
                   8305:                                   line 3 - B would assign 22 points.  
1.497     foxr     8306: 
                   8307: =cut
                   8308: 
                   8309: sub prompt_for_corrections {
1.691     raeburn  8310:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8311:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8312:     my ($current_line,$lines);
                   8313:     my @linenums;
                   8314:     my $questionnum = $question;
1.691     raeburn  8315:     my ($first,$responsenum);
1.503     raeburn  8316:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8317:         $question = $1;
                   8318:         my $subquestion = $2;
1.691     raeburn  8319:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8320:             $responsenum = $respnumlookup->{$question-1};
                   8321:             if (ref($startline) eq 'HASH') {
                   8322:                 $first = $startline->{$question-1};
                   8323:             }
                   8324:         } else {
                   8325:             $responsenum = $question-1;
1.714     raeburn  8326:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8327:         }
                   8328:         $current_line = $first + 1 ;
                   8329:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8330:         my $subcount = 1;
                   8331:         while ($subcount<$subquestion) {
                   8332:             $current_line += $subans[$subcount-1];
                   8333:             $subcount ++;
                   8334:         }
                   8335:         $lines = $subans[$subquestion-1];
                   8336:     } else {
1.691     raeburn  8337:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8338:             $responsenum = $respnumlookup->{$question-1};
                   8339:             if (ref($startline) eq 'HASH') { 
                   8340:                 $first = $startline->{$question-1};
                   8341:             }
                   8342:         } else {
                   8343:             $responsenum = $question-1;
                   8344:             $first = $first_bubble_line{$responsenum};
                   8345:         }
                   8346:         $current_line = $first + 1;
                   8347:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8348:     }
1.497     foxr     8349:     if ($lines > 1) {
1.503     raeburn  8350:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8351:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8352:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8353:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8354:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8355:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8356:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8357:             $r->print(
                   8358:                 &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)
                   8359:                .'<br /><br />'
                   8360:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8361:                .'<br />'
                   8362:                .&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.')
                   8363:                .'<br />'
                   8364:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8365:                .'<br /><br />'
                   8366:             );
1.503     raeburn  8367:         } else {
                   8368:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8369:         }
1.497     foxr     8370:     }
                   8371:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8372:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8373: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8374: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8375:         push(@linenums,$current_line);
1.497     foxr     8376: 	$current_line++;
                   8377:     }
                   8378:     if ($lines > 1) {
                   8379: 	$r->print("<hr /><br />");
                   8380:     }
1.503     raeburn  8381:     return @linenums;
1.157     albertel 8382: }
1.423     albertel 8383: 
                   8384: =pod
                   8385: 
                   8386: =item scantron_bubble_selector
                   8387:   
                   8388:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8389:    possibly showing the existing the selected bubbles if known
1.423     albertel 8390: 
                   8391:  Arguments:
                   8392:     $r           - Apache request object
1.754     raeburn  8393:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8394:     $line        - Number of the line being displayed.
1.503     raeburn  8395:     $questionnum - Question number (may include subquestion)
                   8396:     $error       - Type of error.
1.497     foxr     8397:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8398: 
                   8399: =cut
                   8400: 
1.157     albertel 8401: sub scantron_bubble_selector {
1.503     raeburn  8402:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8403:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8404: 
                   8405:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8406:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8407:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8408:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8409:             $max=$$scan_config{'BubblesPerRow'};
                   8410:             if (($scmode eq 'number') && ($max > 10)) {
                   8411:                 $max = 10;
                   8412:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8413:                 $max = 26;
                   8414:             }
                   8415:         } else {
                   8416:             $max = 10;
                   8417:         }
                   8418:     }
1.274     albertel 8419: 
1.157     albertel 8420:     my @alphabet=('A'..'Z');
1.503     raeburn  8421:     $r->print(&Apache::loncommon::start_data_table().
                   8422:               &Apache::loncommon::start_data_table_row());
                   8423:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8424:     for (my $i=0;$i<$max+1;$i++) {
                   8425: 	$r->print("\n".'<td align="center">');
                   8426: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8427: 	else { $r->print('&nbsp;'); }
                   8428: 	$r->print('</td>');
                   8429:     }
1.503     raeburn  8430:     $r->print(&Apache::loncommon::end_data_table_row().
                   8431:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8432:     for (my $i=0;$i<$max;$i++) {
                   8433: 	$r->print("\n".
                   8434: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8435: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8436:     }
1.503     raeburn  8437:     my $nobub_checked = ' ';
                   8438:     if ($error eq 'missingbubble') {
                   8439:         $nobub_checked = ' checked = "checked" ';
                   8440:     }
                   8441:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8442: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8443:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8444:               $line.'" value="'.$questionnum.'" /></td>');
                   8445:     $r->print(&Apache::loncommon::end_data_table_row().
                   8446:               &Apache::loncommon::end_data_table());
1.157     albertel 8447: }
                   8448: 
1.423     albertel 8449: =pod
                   8450: 
                   8451: =item num_matches
                   8452: 
1.424     albertel 8453:    Counts the number of characters that are the same between the two arguments.
                   8454: 
                   8455:  Arguments:
                   8456:    $orig - CODE from the scanline
                   8457:    $code - CODE to match against
                   8458: 
                   8459:  Returns:
                   8460:    $count - integer count of the number of same characters between the
                   8461:             two arguments
                   8462: 
1.423     albertel 8463: =cut
                   8464: 
1.194     albertel 8465: sub num_matches {
                   8466:     my ($orig,$code) = @_;
                   8467:     my @code=split(//,$code);
                   8468:     my @orig=split(//,$orig);
                   8469:     my $same=0;
                   8470:     for (my $i=0;$i<scalar(@code);$i++) {
                   8471: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8472:     }
                   8473:     return $same;
                   8474: }
                   8475: 
1.423     albertel 8476: =pod
                   8477: 
                   8478: =item scantron_get_closely_matching_CODEs
                   8479: 
1.424     albertel 8480:    Cycles through all CODEs and finds the set that has the greatest
                   8481:    number of same characters as the provided CODE
                   8482: 
                   8483:  Arguments:
                   8484:    $allcodes - hash ref returned by &get_codes()
                   8485:    $CODE     - CODE from the current scanline
                   8486: 
                   8487:  Returns:
                   8488:    2 element list
                   8489:     - first elements is number of how closely matching the best fit is 
                   8490:       (5 means best set has 5 matching characters)
                   8491:     - second element is an arrary ref containing the set of valid CODEs
                   8492:       that best fit the passed in CODE
                   8493: 
1.423     albertel 8494: =cut
                   8495: 
1.194     albertel 8496: sub scantron_get_closely_matching_CODEs {
                   8497:     my ($allcodes,$CODE)=@_;
                   8498:     my @CODEs;
                   8499:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8500: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8501:     }
                   8502: 
                   8503:     return ($#CODEs,$CODEs[-1]);
                   8504: }
                   8505: 
1.423     albertel 8506: =pod
                   8507: 
                   8508: =item get_codes
                   8509: 
1.424     albertel 8510:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8511:    set of remembered CODEs.
                   8512: 
                   8513:  Arguments:
                   8514:   $old_name - name of the set of remembered CODEs
                   8515:   $cdom     - domain of the course
                   8516:   $cnum     - internal course name
                   8517: 
                   8518:  Returns:
                   8519:   %allcodes - keys are the valid CODEs, values are all 1
                   8520: 
1.423     albertel 8521: =cut
                   8522: 
1.194     albertel 8523: sub get_codes {
1.280     foxr     8524:     my ($old_name, $cdom, $cnum) = @_;
                   8525:     if (!$old_name) {
                   8526: 	$old_name=$env{'form.scantron_CODElist'};
                   8527:     }
                   8528:     if (!$cdom) {
                   8529: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8530:     }
                   8531:     if (!$cnum) {
                   8532: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8533:     }
1.278     albertel 8534:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8535: 				    $cdom,$cnum);
                   8536:     my %allcodes;
                   8537:     if ($result{"type\0$old_name"} eq 'number') {
                   8538: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8539:     } else {
                   8540: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8541:     }
1.194     albertel 8542:     return %allcodes;
                   8543: }
                   8544: 
1.423     albertel 8545: =pod
                   8546: 
                   8547: =item scantron_validate_CODE
                   8548: 
1.424     albertel 8549:    Validates all scanlines in the selected file to not have any
                   8550:    invalid or underspecified CODEs and that none of the codes are
                   8551:    duplicated if this was requested.
                   8552: 
1.423     albertel 8553: =cut
                   8554: 
1.157     albertel 8555: sub scantron_validate_CODE {
                   8556:     my ($r,$currentphase) = @_;
1.754     raeburn  8557:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8558:     if ($scantron_config{'CODElocation'} &&
                   8559: 	$scantron_config{'CODEstart'} &&
                   8560: 	$scantron_config{'CODElength'}) {
1.257     albertel 8561: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8562: 	    &FIXME_blow_up()
                   8563: 	}
                   8564:     } else {
                   8565: 	return (0,$currentphase+1);
                   8566:     }
                   8567:     
                   8568:     my %usedCODEs;
                   8569: 
1.194     albertel 8570:     my %allcodes=&get_codes();
1.186     albertel 8571: 
1.582     raeburn  8572:     my $nav_error;
1.649     raeburn  8573:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8574:     if ($nav_error) {
                   8575:         $r->print(&navmap_errormsg());
                   8576:         return(1,$currentphase);
                   8577:     }
1.447     foxr     8578: 
1.186     albertel 8579:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8580:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8581: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8582: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8583: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8584: 						 $scan_data);
                   8585: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8586: 	my $error=0;
1.224     albertel 8587: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8588: 	    &scantron_get_correction($r,$i,$scan_record,
                   8589: 				     \%scantron_config,
                   8590: 				     $line,'incorrectCODE',\%allcodes);
                   8591: 	    return(1,$currentphase);
                   8592: 	}
1.221     albertel 8593: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8594: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8595: 	    &scantron_get_correction($r,$i,$scan_record,
                   8596: 				     \%scantron_config,
1.194     albertel 8597: 				     $line,'incorrectCODE',\%allcodes);
                   8598: 	    return(1,$currentphase);
1.186     albertel 8599: 	}
1.214     albertel 8600: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8601: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8602: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8603: 	    &scantron_get_correction($r,$i,$scan_record,
                   8604: 				     \%scantron_config,
1.194     albertel 8605: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8606: 	    return(1,$currentphase);
1.186     albertel 8607: 	}
1.524     raeburn  8608: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8609:     }
1.157     albertel 8610:     return (0,$currentphase+1);
                   8611: }
                   8612: 
1.423     albertel 8613: =pod
                   8614: 
                   8615: =item scantron_validate_doublebubble
                   8616: 
1.424     albertel 8617:    Validates all scanlines in the selected file to not have any
                   8618:    bubble lines with multiple bubbles marked.
                   8619: 
1.423     albertel 8620: =cut
                   8621: 
1.157     albertel 8622: sub scantron_validate_doublebubble {
                   8623:     my ($r,$currentphase) = @_;
                   8624:     #get student info
                   8625:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8626:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8627:     my (undef,undef,$sequence)=
                   8628:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8629: 
                   8630:     #get scantron line setup
1.754     raeburn  8631:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8632:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8633: 
                   8634:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8635:     unless (ref($navmap)) {
                   8636:         $r->print(&navmap_errormsg());
                   8637:         return(1,$currentphase);
                   8638:     }
                   8639:     my $map=$navmap->getResourceByUrl($sequence);
                   8640:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8641:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8642:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8643:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8644: 
1.583     raeburn  8645:     my $nav_error;
1.691     raeburn  8646:     if (ref($map)) {
                   8647:         $randomorder = $map->randomorder();
                   8648:         $randompick = $map->randompick();
                   8649:         if ($randomorder || $randompick) {
                   8650:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8651:             if ($nav_error) {
                   8652:                 $r->print(&navmap_errormsg());
                   8653:                 return(1,$currentphase);
                   8654:             }
                   8655:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8656:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8657:         }
                   8658:     } else {
                   8659:         $r->print(&navmap_errormsg());
                   8660:         return(1,$currentphase);
                   8661:     }
                   8662: 
1.649     raeburn  8663:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8664:     if ($nav_error) {
                   8665:         $r->print(&navmap_errormsg());
                   8666:         return(1,$currentphase);
                   8667:     }
1.447     foxr     8668: 
1.157     albertel 8669:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8670: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8671: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8672: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8673: 						 $scan_data,undef,\%idmap,$randomorder,
                   8674:                                                  $randompick,$sequence,\@master_seq,
                   8675:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8676:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8677: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8678: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8679: 				 'doublebubble',
1.691     raeburn  8680: 				 $$scan_record{'scantron.doubleerror'},
                   8681:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8682:     	return (1,$currentphase);
                   8683:     }
                   8684:     return (0,$currentphase+1);
                   8685: }
                   8686: 
1.423     albertel 8687: 
1.503     raeburn  8688: sub scantron_get_maxbubble {
1.649     raeburn  8689:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8690:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8691: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8692: 	&restore_bubble_lines();
1.257     albertel 8693: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8694:     }
1.330     albertel 8695: 
1.447     foxr     8696:     my (undef, undef, $sequence) =
1.257     albertel 8697: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8698: 
1.447     foxr     8699:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8700:     unless (ref($navmap)) {
                   8701:         if (ref($nav_error)) {
                   8702:             $$nav_error = 1;
                   8703:         }
1.591     raeburn  8704:         return;
1.582     raeburn  8705:     }
1.191     albertel 8706:     my $map=$navmap->getResourceByUrl($sequence);
                   8707:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8708:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8709: 
                   8710:     &Apache::lonxml::clear_problem_counter();
                   8711: 
1.557     raeburn  8712:     my $uname       = $env{'user.name'};
                   8713:     my $udom        = $env{'user.domain'};
1.435     foxr     8714:     my $cid         = $env{'request.course.id'};
                   8715:     my $total_lines = 0;
                   8716:     %bubble_lines_per_response = ();
1.447     foxr     8717:     %first_bubble_line         = ();
1.503     raeburn  8718:     %subdivided_bubble_lines   = ();
                   8719:     %responsetype_per_response = ();
1.691     raeburn  8720:     %masterseq_id_responsenum  = ();
1.554     raeburn  8721: 
1.447     foxr     8722:     my $response_number = 0;
                   8723:     my $bubble_line     = 0;
1.191     albertel 8724:     foreach my $resource (@resources) {
1.691     raeburn  8725:         my $resid = $resource->id(); 
1.672     raeburn  8726:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8727:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8728:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8729: 	    foreach my $part_id (@{$parts}) {
                   8730:                 my $lines;
                   8731: 
                   8732: 	        # TODO - make this a persistent hash not an array.
                   8733: 
                   8734:                 # optionresponse, matchresponse and rankresponse type items 
                   8735:                 # render as separate sub-questions in exam mode.
                   8736:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8737:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8738:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8739:                     my ($numbub,$numshown);
                   8740:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8741:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8742:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8743:                         }
                   8744:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8745:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8746:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8747:                         }
                   8748:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8749:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8750:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8751:                         }
                   8752:                     }
                   8753:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8754:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8755:                     }
1.649     raeburn  8756:                     my $bubbles_per_row =
                   8757:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8758:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8759:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8760:                         $inner_bubble_lines++;
                   8761:                     }
                   8762:                     for (my $i=0; $i<$numshown; $i++) {
                   8763:                         $subdivided_bubble_lines{$response_number} .= 
                   8764:                             $inner_bubble_lines.',';
                   8765:                     }
                   8766:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8767:                     $lines = $numshown * $inner_bubble_lines;
                   8768:                 } else {
                   8769:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8770:                 }
1.542     raeburn  8771: 
                   8772:                 $first_bubble_line{$response_number} = $bubble_line;
                   8773: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8774:                 $responsetype_per_response{$response_number} = 
                   8775:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8776:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8777: 	        $response_number++;
                   8778: 
                   8779: 	        $bubble_line +=  $lines;
                   8780: 	        $total_lines +=  $lines;
                   8781: 	    }
                   8782:         }
                   8783:     }
1.552     raeburn  8784:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8785: 
                   8786:     &save_bubble_lines();
                   8787:     $env{'form.scantron_maxbubble'} =
                   8788: 	$total_lines;
                   8789:     return $env{'form.scantron_maxbubble'};
                   8790: }
1.523     raeburn  8791: 
1.649     raeburn  8792: sub bubblesheet_bubbles_per_row {
                   8793:     my ($scantron_config) = @_;
                   8794:     my $bubbles_per_row;
                   8795:     if (ref($scantron_config) eq 'HASH') {
                   8796:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8797:     }
                   8798:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8799:         $bubbles_per_row = 10;
                   8800:     }
                   8801:     return $bubbles_per_row;
                   8802: }
                   8803: 
1.157     albertel 8804: sub scantron_validate_missingbubbles {
                   8805:     my ($r,$currentphase) = @_;
                   8806:     #get student info
                   8807:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8808:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8809:     my (undef,undef,$sequence)=
                   8810:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8811: 
                   8812:     #get scantron line setup
1.754     raeburn  8813:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8814:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8815: 
                   8816:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8817:     unless (ref($navmap)) {
                   8818:         $r->print(&navmap_errormsg());
                   8819:         return(1,$currentphase);
                   8820:     }
                   8821: 
                   8822:     my $map=$navmap->getResourceByUrl($sequence);
                   8823:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8824:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8825:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8826:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8827: 
1.582     raeburn  8828:     my $nav_error;
1.691     raeburn  8829:     if (ref($map)) {
                   8830:         $randomorder = $map->randomorder();
                   8831:         $randompick = $map->randompick();
                   8832:         if ($randomorder || $randompick) {
                   8833:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8834:             if ($nav_error) {
                   8835:                 $r->print(&navmap_errormsg());
                   8836:                 return(1,$currentphase);
                   8837:             }
                   8838:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8839:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8840:         }
                   8841:     } else {
                   8842:         $r->print(&navmap_errormsg());
                   8843:         return(1,$currentphase);
                   8844:     }
                   8845: 
                   8846: 
1.649     raeburn  8847:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8848:     if ($nav_error) {
1.691     raeburn  8849:         $r->print(&navmap_errormsg());
1.693     raeburn  8850:         return(1,$currentphase);
1.582     raeburn  8851:     }
1.691     raeburn  8852: 
1.157     albertel 8853:     if (!$max_bubble) { $max_bubble=2**31; }
                   8854:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8855: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8856: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8857: 	my $scan_record =
                   8858:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8859: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8860:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8861:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8862: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8863: 	my @to_correct;
1.470     foxr     8864: 	
                   8865: 	# Probably here's where the error is...
                   8866: 
1.157     albertel 8867: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8868:             my $lastbubble;
                   8869:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8870:                my $question = $1;
                   8871:                my $subquestion = $2;
1.691     raeburn  8872:                my ($first,$responsenum);
                   8873:                if ($randomorder || $randompick) {
                   8874:                    $responsenum = $respnumlookup{$question-1};
                   8875:                    $first = $startline{$question-1};
                   8876:                } else {
                   8877:                    $responsenum = $question-1; 
                   8878:                    $first = $first_bubble_line{$responsenum};
                   8879:                }
                   8880:                if (!defined($first)) { next; }
                   8881:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8882:                my $subcount = 1;
                   8883:                while ($subcount<$subquestion) {
                   8884:                    $first += $subans[$subcount-1];
                   8885:                    $subcount ++;
                   8886:                }
                   8887:                my $count = $subans[$subquestion-1];
                   8888:                $lastbubble = $first + $count;
                   8889:             } else {
1.691     raeburn  8890:                my ($first,$responsenum);
                   8891:                if ($randomorder || $randompick) {
                   8892:                    $responsenum = $respnumlookup{$missing-1};
                   8893:                    $first = $startline{$missing-1};
                   8894:                } else {
                   8895:                    $responsenum = $missing-1;
                   8896:                    $first = $first_bubble_line{$responsenum};
                   8897:                }
                   8898:                if (!defined($first)) { next; }
                   8899:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8900:             }
                   8901:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8902: 	    push(@to_correct,$missing);
                   8903: 	}
                   8904: 	if (@to_correct) {
                   8905: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8906: 				     $line,'missingbubble',\@to_correct,
                   8907:                                      $randomorder,$randompick,\%respnumlookup,
                   8908:                                      \%startline);
1.157     albertel 8909: 	    return (1,$currentphase);
                   8910: 	}
                   8911: 
                   8912:     }
                   8913:     return (0,$currentphase+1);
                   8914: }
                   8915: 
1.663     raeburn  8916: sub hand_bubble_option {
                   8917:     my (undef, undef, $sequence) =
                   8918:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8919:     return if ($sequence eq '');
                   8920:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8921:     unless (ref($navmap)) {
                   8922:         return;
                   8923:     }
                   8924:     my $needs_hand_bubbles;
                   8925:     my $map=$navmap->getResourceByUrl($sequence);
                   8926:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8927:     foreach my $res (@resources) {
                   8928:         if (ref($res)) {
                   8929:             if ($res->is_problem()) {
                   8930:                 my $partlist = $res->parts();
                   8931:                 foreach my $part (@{ $partlist }) {
                   8932:                     my @types = $res->responseType($part);
                   8933:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8934:                         $needs_hand_bubbles = 1;
                   8935:                         last;
                   8936:                     }
                   8937:                 }
                   8938:             }
                   8939:         }
                   8940:     }
                   8941:     if ($needs_hand_bubbles) {
1.754     raeburn  8942:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8943:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8944:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8945:                &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 />').
                   8946:                '<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;'.
1.722     raeburn  8947:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8948:     }
                   8949:     return;
                   8950: }
1.423     albertel 8951: 
1.82      albertel 8952: sub scantron_process_students {
1.608     www      8953:     my ($r,$symb) = @_;
1.513     foxr     8954: 
1.257     albertel 8955:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8956:     if (!$symb) {
                   8957: 	return '';
                   8958:     }
1.324     albertel 8959:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8960: 
1.754     raeburn  8961:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8962:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8963:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8964:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8965:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8966:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8967:     unless (ref($navmap)) {
                   8968:         $r->print(&navmap_errormsg());
                   8969:         return '';
1.691     raeburn  8970:     }
1.83      albertel 8971:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8972:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8973:         %grader_randomlists_by_symb);
1.677     raeburn  8974:     if (ref($map)) {
                   8975:         $randomorder = $map->randomorder();
1.689     raeburn  8976:         $randompick = $map->randompick();
1.691     raeburn  8977:     } else {
                   8978:         $r->print(&navmap_errormsg());
                   8979:         return '';
1.677     raeburn  8980:     }
1.691     raeburn  8981:     my $nav_error;
1.83      albertel 8982:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8983:     if ($randomorder || $randompick) {
                   8984:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8985:         if ($nav_error) {
                   8986:             $r->print(&navmap_errormsg());
                   8987:             return '';
                   8988:         }
                   8989:     }
1.557     raeburn  8990:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8991:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8992: 
1.554     raeburn  8993:     my ($uname,$udom);
1.82      albertel 8994:     my $result= <<SCANTRONFORM;
1.81      albertel 8995: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8996:   <input type="hidden" name="command" value="scantron_configphase" />
                   8997:   $default_form_data
                   8998: SCANTRONFORM
1.82      albertel 8999:     $r->print($result);
                   9000: 
1.770     raeburn  9001:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 9002:     my @delayqueue;
1.542     raeburn  9003:     my (%completedstudents,%scandata);
1.770     raeburn  9004: 
1.520     www      9005:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 9006:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9007:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   9008:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  9009:     $r->print('<br />');
1.140     albertel 9010:     my $start=&Time::HiRes::time();
1.158     albertel 9011:     my $i=-1;
1.542     raeburn  9012:     my $started;
1.447     foxr     9013: 
1.649     raeburn  9014:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9015:     if ($nav_error) {
                   9016:         $r->print(&navmap_errormsg());
                   9017:         return '';
                   9018:     }
                   9019: 
1.513     foxr     9020:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   9021:     # the user and return.
                   9022: 
                   9023:     if ($ssi_error) {
                   9024: 	$r->print("</form>");
                   9025: 	&ssi_print_error($r);
1.520     www      9026:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     9027: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   9028:     }
1.447     foxr     9029: 
1.755     raeburn  9030:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  9031:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  9032:     my %orderedforcode;
1.542     raeburn  9033: 
1.157     albertel 9034:     while ($i<$scanlines->{'count'}) {
                   9035:  	($uname,$udom)=('','');
                   9036:  	$i++;
1.200     albertel 9037:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 9038:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 9039: 	if ($started) {
1.667     www      9040: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 9041: 	}
                   9042: 	$started=1;
1.691     raeburn  9043:         my %respnumlookup = ();
                   9044:         my %startline = ();
                   9045:         my $total;
1.157     albertel 9046:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  9047:                                                  $scan_data,undef,\%idmap,$randomorder,
                   9048:                                                  $randompick,$sequence,\@master_seq,
                   9049:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   9050:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   9051:                                                  \$total);
1.157     albertel 9052:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9053:  					      \%idmap,$i)) {
                   9054:   	    &scantron_add_delay(\@delayqueue,$line,
                   9055:  				'Unable to find a student that matches',1);
                   9056:  	    next;
                   9057:   	}
                   9058:  	if (exists $completedstudents{$uname}) {
                   9059:  	    &scantron_add_delay(\@delayqueue,$line,
                   9060:  				'Student '.$uname.' has multiple sheets',2);
                   9061:  	    next;
                   9062:  	}
1.677     raeburn  9063:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  9064:         if (($checksec ne '') && ($checksec ne $usec)) {
                   9065:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   9066:                 &scantron_add_delay(\@delayqueue,$line,
                   9067:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   9068:                 next;
                   9069:             }
                   9070:         }
1.677     raeburn  9071:         my $user = $uname.':'.$usec;
1.157     albertel 9072:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 9073: 
1.677     raeburn  9074:         my $scancode;
                   9075:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9076:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9077:             $scancode = $scan_record->{'scantron.CODE'};
                   9078:         } else {
                   9079:             $scancode = '';
                   9080:         }
                   9081: 
                   9082:         my @mapresources = @resources;
1.689     raeburn  9083:         if ($randomorder || $randompick) {
1.678     raeburn  9084:             @mapresources = 
1.691     raeburn  9085:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9086:                              \%orderedforcode);
1.677     raeburn  9087:         }
1.586     raeburn  9088:         my (%partids_by_symb,$res_error);
1.677     raeburn  9089:         foreach my $resource (@mapresources) {
1.586     raeburn  9090:             my $ressymb;
                   9091:             if (ref($resource)) {
                   9092:                 $ressymb = $resource->symb();
                   9093:             } else {
                   9094:                 $res_error = 1;
                   9095:                 last;
                   9096:             }
1.557     raeburn  9097:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9098:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9099:                 my $currcode;
                   9100:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9101:                     $currcode = $scancode;
                   9102:                 }
1.557     raeburn  9103:                 my ($analysis,$parts) =
1.672     raeburn  9104:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  9105:                                               $uname,$udom,undef,$bubbles_per_row,
                   9106:                                               $currcode);
1.557     raeburn  9107:                 $partids_by_symb{$ressymb} = $parts;
                   9108:             } else {
                   9109:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   9110:             }
1.554     raeburn  9111:         }
                   9112: 
1.586     raeburn  9113:         if ($res_error) {
                   9114:             &scantron_add_delay(\@delayqueue,$line,
                   9115:                                 'An error occurred while grading student '.$uname,2);
                   9116:             next;
                   9117:         }
                   9118: 
1.330     albertel 9119: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  9120:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 9121: 
                   9122: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   9123: 	    &scantron_putfile($scanlines,$scan_data);
                   9124: 	}
1.161     albertel 9125: 	
1.542     raeburn  9126:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9127:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  9128:                                    $bubbles_per_row,$randomorder,$randompick,
                   9129:                                    \%respnumlookup,\%startline) 
                   9130:             eq 'ssi_error') {
1.542     raeburn  9131:             $ssi_error = 0; # So end of handler error message does not trigger.
                   9132:             $r->print("</form>");
                   9133:             &ssi_print_error($r);
                   9134:             &Apache::lonnet::remove_lock($lock);
                   9135:             return '';      # Why return ''?  Beats me.
                   9136:         }
1.513     foxr     9137: 
1.692     raeburn  9138:         if (($scancode) && ($randomorder || $randompick)) {
                   9139:             my $parmresult =
                   9140:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   9141:                                                        '0_examcode',2,$scancode,
                   9142:                                                        'string_examcode',$uname,
                   9143:                                                        $udom);
                   9144:         }
1.140     albertel 9145: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  9146:         if ($env{'form.verifyrecord'}) {
                   9147:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  9148:             if ($randompick) {
                   9149:                 if ($total) {
                   9150:                     $lastpos = $total*$scantron_config{'Qlength'};
                   9151:                 }
                   9152:             }
                   9153: 
1.542     raeburn  9154:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9155:             chomp($studentdata);
                   9156:             $studentdata =~ s/\r$//;
                   9157:             my $studentrecord = '';
                   9158:             my $counter = -1;
1.677     raeburn  9159:             foreach my $resource (@mapresources) {
1.554     raeburn  9160:                 my $ressymb = $resource->symb();
1.542     raeburn  9161:                 ($counter,my $recording) =
                   9162:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9163:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9164:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9165:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9166:                 $studentrecord .= $recording;
                   9167:             }
                   9168:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9169:                 &Apache::lonxml::clear_problem_counter();
                   9170:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9171:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9172:                                            $bubbles_per_row,$randomorder,$randompick,
                   9173:                                            \%respnumlookup,\%startline) 
                   9174:                     eq 'ssi_error') {
1.554     raeburn  9175:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9176:                     $r->print("</form>");
                   9177:                     &ssi_print_error($r);
                   9178:                     &Apache::lonnet::remove_lock($lock);
                   9179:                     delete($completedstudents{$uname});
                   9180:                     return '';
                   9181:                 }
1.542     raeburn  9182:                 $counter = -1;
                   9183:                 $studentrecord = '';
1.677     raeburn  9184:                 foreach my $resource (@mapresources) {
1.554     raeburn  9185:                     my $ressymb = $resource->symb();
1.542     raeburn  9186:                     ($counter,my $recording) =
                   9187:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9188:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9189:                                                  \%scantron_config,\%lettdig,$numletts,
                   9190:                                                  $randomorder,$randompick,\%respnumlookup,
                   9191:                                                  \%startline);
1.542     raeburn  9192:                     $studentrecord .= $recording;
                   9193:                 }
                   9194:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9195:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9196:                     if ($scancode eq '') {
1.658     bisitz   9197:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9198:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9199:                     } else {
1.658     bisitz   9200:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9201:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9202:                     }
                   9203:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9204:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9205:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9206:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9207:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9208:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9209:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9210:                               &Apache::loncommon::end_data_table_row().
                   9211:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9212:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9213:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9214:                               &Apache::loncommon::end_data_table_row().
                   9215:                               &Apache::loncommon::end_data_table().'</p>');
                   9216:                 } else {
                   9217:                     $r->print('<br /><span class="LC_warning">'.
                   9218:                              &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 />'.
                   9219:                              &mt("As a consequence, this user's submission history records two tries.").
                   9220:                                  '</span><br />');
                   9221:                 }
                   9222:             }
                   9223:         }
1.543     raeburn  9224:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9225:     } continue {
1.330     albertel 9226: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9227: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9228:     }
1.140     albertel 9229:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9230:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9231: #    my $lasttime = &Time::HiRes::time()-$start;
                   9232: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9233: 
1.200     albertel 9234:     $r->print("</form>");
1.157     albertel 9235:     return '';
1.75      albertel 9236: }
1.157     albertel 9237: 
1.557     raeburn  9238: sub graders_resources_pass {
1.649     raeburn  9239:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9240:         $bubbles_per_row) = @_;
1.557     raeburn  9241:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9242:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9243:         foreach my $resource (@{$resources}) {
                   9244:             my $ressymb = $resource->symb();
                   9245:             my ($analysis,$parts) =
                   9246:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9247:                                           $env{'user.name'},$env{'user.domain'},
                   9248:                                           1,$bubbles_per_row);
1.557     raeburn  9249:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9250:             if (ref($analysis) eq 'HASH') {
                   9251:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9252:                     $grader_randomlists_by_symb->{$ressymb} =
                   9253:                         $analysis->{'parts_withrandomlist'};
                   9254:                 }
                   9255:             }
                   9256:         }
                   9257:     }
                   9258:     return;
                   9259: }
                   9260: 
1.678     raeburn  9261: =pod
                   9262: 
                   9263: =item users_order
                   9264: 
                   9265:   Returns array of resources in current map, ordered based on either CODE,
                   9266:   if this is a CODEd exam, or based on student's identity if this is a 
                   9267:   "NAMEd" exam.
                   9268: 
1.691     raeburn  9269:   Should be used when randomorder and/or randompick applied when the 
                   9270:   corresponding exam was printed, prior to students completing bubblesheets 
                   9271:   for the version of the exam the student received.
1.678     raeburn  9272: 
                   9273: =cut
                   9274: 
                   9275: sub users_order  {
1.691     raeburn  9276:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9277:     my @mapresources;
1.691     raeburn  9278:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9279:         return @mapresources;
1.691     raeburn  9280:     }
                   9281:     if ($scancode) {
                   9282:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9283:             @mapresources = @{$orderedforcode->{$scancode}};
                   9284:         } else {
                   9285:             $env{'form.CODE'} = $scancode;
                   9286:             my $actual_seq =
                   9287:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9288:                                                                $master_seq,
                   9289:                                                                $user,$scancode,1);
                   9290:             if (ref($actual_seq) eq 'ARRAY') {
                   9291:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9292:                 if (ref($orderedforcode) eq 'HASH') {
                   9293:                     if (@mapresources > 0) { 
                   9294:                         $orderedforcode->{$scancode} = \@mapresources;
                   9295:                     }
                   9296:                 }
                   9297:             }
                   9298:             delete($env{'form.CODE'});
1.678     raeburn  9299:         }
                   9300:     } else {
                   9301:         my $actual_seq =
                   9302:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9303:                                                            $master_seq,
1.688     raeburn  9304:                                                            $user,undef,1);
1.678     raeburn  9305:         if (ref($actual_seq) eq 'ARRAY') {
                   9306:             @mapresources = 
                   9307:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9308:         }
1.691     raeburn  9309:     }
                   9310:     return @mapresources;
1.678     raeburn  9311: }
                   9312: 
1.542     raeburn  9313: sub grade_student_bubbles {
1.691     raeburn  9314:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9315:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9316:     my $uselookup = 0;
                   9317:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9318:         (ref($startline) eq 'HASH')) {
                   9319:         $uselookup = 1;
                   9320:     }
                   9321: 
1.554     raeburn  9322:     if (ref($resources) eq 'ARRAY') {
                   9323:         my $count = 0;
                   9324:         foreach my $resource (@{$resources}) {
                   9325:             my $ressymb = $resource->symb();
                   9326:             my %form = ('submitted'      => 'scantron',
                   9327:                         'grade_target'   => 'grade',
                   9328:                         'grade_username' => $uname,
                   9329:                         'grade_domain'   => $udom,
                   9330:                         'grade_courseid' => $env{'request.course.id'},
                   9331:                         'grade_symb'     => $ressymb,
                   9332:                         'CODE'           => $scancode
                   9333:                        );
1.649     raeburn  9334:             if ($bubbles_per_row ne '') {
                   9335:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9336:             }
1.663     raeburn  9337:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9338:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9339:             }
1.554     raeburn  9340:             if (ref($parts) eq 'HASH') {
                   9341:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9342:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9343:                         if ($uselookup) {
                   9344:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9345:                         } else {
                   9346:                             $form{'scantron_questnum_start.'.$part} =
                   9347:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9348:                         }
1.554     raeburn  9349:                         $count++;
                   9350:                     }
                   9351:                 }
                   9352:             }
                   9353:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9354:             return 'ssi_error' if ($ssi_error);
                   9355:             last if (&Apache::loncommon::connection_aborted($r));
                   9356:         }
1.542     raeburn  9357:     }
                   9358:     return;
                   9359: }
                   9360: 
1.157     albertel 9361: sub scantron_upload_scantron_data {
1.767     raeburn  9362:     my ($r,$symb) = @_;
1.565     raeburn  9363:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9364:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9365:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9366:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9367:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9368: 							  'domainid',
1.565     raeburn  9369: 							  'coursename',$dom);
                   9370:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9371:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9372:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9373:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9374:     &js_escape(\$nofile_alert);
1.579     raeburn  9375:     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.736     damieng  9376:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9377:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9378:     function checkUpload(formname) {
                   9379: 	if (formname.upfile.value == "") {
1.579     raeburn  9380: 	    alert("'.$nofile_alert.'");
1.157     albertel 9381: 	    return false;
                   9382: 	}
1.565     raeburn  9383:         if (formname.courseid.value == "") {
1.579     raeburn  9384:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9385:             return false;
                   9386:         }
1.157     albertel 9387: 	formname.submit();
                   9388:     }
1.565     raeburn  9389: 
                   9390:     function ToSyllabus() {
                   9391:         var cdom = '."'$dom'".';
                   9392:         var cnum = document.rules.courseid.value;
                   9393:         if (cdom == "" || cdom == null) {
                   9394:             return;
                   9395:         }
                   9396:         if (cnum == "" || cnum == null) {
                   9397:            return;
                   9398:         }
                   9399:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9400:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9401:         return;
                   9402:     }
                   9403: 
1.754     raeburn  9404:     '.$formatjs.'
1.597     wenzelju 9405: '));
                   9406:     $r->print('
1.648     bisitz   9407: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9408: 
1.492     albertel 9409: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9410: '.$default_form_data.
                   9411:   &Apache::lonhtmlcommon::start_pick_box().
                   9412:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9413:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9414:   &Apache::lonhtmlcommon::row_closure().
                   9415:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9416:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9417:   &Apache::lonhtmlcommon::row_closure().
                   9418:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9419:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9420:   &Apache::lonhtmlcommon::row_closure());
                   9421:     if ($formatoptions) {
                   9422:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9423:                   &Apache::lonhtmlcommon::row_closure());
                   9424:     }
                   9425:     $r->print(
1.565     raeburn  9426:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9427:   '<input type="file" name="upfile" size="50" />'.
                   9428:   &Apache::lonhtmlcommon::row_closure(1).
                   9429:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9430: 
1.492     albertel 9431: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9432: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9433: </form>
1.492     albertel 9434: ');
1.157     albertel 9435:     return '';
                   9436: }
                   9437: 
1.754     raeburn  9438: sub scantron_upload_dataformat {
                   9439:     my ($dom) = @_;
                   9440:     my ($formatoptions,$formattitle,$formatjs);
                   9441:     $formatjs = <<'END';
                   9442: function toggleScantab(form) {
                   9443:    return;
                   9444: }
                   9445: END
                   9446:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9447:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9448:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9449:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9450:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9451:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9452:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9453:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9454:                             my ($onclick,$formatextra,$singleline);
                   9455:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9456:                             my $count = 0;
                   9457:                             foreach my $line (@lines) {
                   9458:                                 next if ($line =~ /^#/);
                   9459:                                 $singleline = $line;
                   9460:                                 $count ++;
                   9461:                             }
                   9462:                             if ($count > 1) {
                   9463:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9464:                                                '<span class="LC_nobreak">'.
                   9465:                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9466:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9467:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9468:                                 $formatjs = <<"END";
1.754     raeburn  9469: function toggleScantab(form) {
                   9470:     var divid = 'bubbletype';
                   9471:     if (document.getElementById(divid)) {
                   9472:         var radioname = 'fileformat';
                   9473:         var num = form.elements[radioname].length;
                   9474:         if (num) {
                   9475:             for (var i=0; i<num; i++) {
                   9476:                 if (form.elements[radioname][i].checked) {
                   9477:                     var chosen = form.elements[radioname][i].value;
                   9478:                     if (chosen == 'dat') {
                   9479:                         document.getElementById(divid).style.display = 'none';
                   9480:                     } else if (chosen == 'csv') {
1.757     raeburn  9481:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9482:                     }
                   9483:                 }
                   9484:             }
                   9485:         }
                   9486:     }
                   9487:     return;
                   9488: }
                   9489: 
                   9490: END
1.756     raeburn  9491:                             } elsif ($count == 1) {
                   9492:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9493:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9494:                             }
                   9495:                             $formattitle = &mt('File format');
                   9496:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9497:                                              &mt('Plain Text (no delimiters)').
                   9498:                                              '</label>'.('&nbsp;'x2).
                   9499:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9500:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9501:                         }
                   9502:                     }
                   9503:                 }
                   9504:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9505:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9506:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9507:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9508:                         $formatoptions = &scantron_scantab();
                   9509:                     }
1.754     raeburn  9510:                 }
                   9511:             }
                   9512:         }
                   9513:     }
                   9514:     return ($formatoptions,$formattitle,$formatjs);
                   9515: }
1.423     albertel 9516: 
1.157     albertel 9517: sub scantron_upload_scantron_data_save {
1.767     raeburn  9518:     my ($r,$symb) = @_;
1.182     albertel 9519:     my $doanotherupload=
                   9520: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9521: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9522: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9523: 	'</form>'."\n";
1.257     albertel 9524:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9525: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9526: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9527:         !&Apache::lonnet::allowed('usc',
                   9528:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9529: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9530: 	unless ($symb) {
1.182     albertel 9531: 	    $r->print($doanotherupload);
                   9532: 	}
1.162     albertel 9533: 	return '';
                   9534:     }
1.257     albertel 9535:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9536:     my $uploadedfile;
1.710     bisitz   9537:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9538:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9539:         $r->print(
                   9540:             &Apache::lonhtmlcommon::confirm_success(
                   9541:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9542:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9543:     } else {
1.754     raeburn  9544:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9545:         my $parser;
                   9546:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9547:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9548:                 my $is_csv;
                   9549:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9550:                 if (@possibles > 1) {
                   9551:                     if ($env{'form.fileformat'} eq 'csv') {
                   9552:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9553:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9554:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9555:                                     $is_csv = 1;
                   9556:                                 }
1.754     raeburn  9557:                             }
                   9558:                         }
                   9559:                     }
                   9560:                 } elsif (@possibles == 1) {
                   9561:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9562:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9563:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9564:                                 $is_csv = 1;
                   9565:                             }
1.754     raeburn  9566:                         }
                   9567:                     }
                   9568:                 }
                   9569:                 if ($is_csv) {
                   9570:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9571:                 }
                   9572:             }
                   9573:         }
                   9574:         my $result =
                   9575:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9576:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9577:         if ($result =~ m{^/uploaded/}) {
                   9578:             $r->print(
                   9579:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9580:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9581:                         (length($env{'form.upfile'})-1),
                   9582:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9583:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9584:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9585:                 my $logname = $uploadedfile;
                   9586:                 $logname =~ s/^scantron_orig_//;
                   9587:                 if ($logname ne '') {
                   9588:                     my $now = time;
                   9589:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9590:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9591:                 }
                   9592:             }
1.567     raeburn  9593:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9594:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9595:         } else {
                   9596:             $r->print(
                   9597:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9598:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9599:                           $result,
1.568     raeburn  9600: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9601: 	}
                   9602:     }
1.174     albertel 9603:     if ($symb) {
1.612     www      9604: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9605:     } else {
1.182     albertel 9606: 	$r->print($doanotherupload);
1.174     albertel 9607:     }
1.157     albertel 9608:     return '';
                   9609: }
                   9610: 
1.567     raeburn  9611: sub validate_uploaded_scantron_file {
1.770     raeburn  9612:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9613: 
1.567     raeburn  9614:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9615:     my @lines;
                   9616:     if ($scanlines ne '-1') {
                   9617:         @lines=split("\n",$scanlines,-1);
                   9618:     }
1.770     raeburn  9619:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9620:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9621:     if ($context eq 'download') {
                   9622:         $priv = 'mgr';
                   9623:     } else {
                   9624:         $priv = 'usc';
                   9625:     }
                   9626:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9627:             (($env{'request.course.id'}) &&
                   9628:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9629:         if ($env{'request.course.sec'} ne '') {
                   9630:             unless (&Apache::lonnet::allowed($priv,
                   9631:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9632:                 unless ($context eq 'download') {
                   9633:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9634:                 }
                   9635:                 return $output;
                   9636:             }
                   9637:             ($checksec,@possibles)=&gradable_sections();
                   9638:         }
                   9639:     }
1.567     raeburn  9640:     if (@lines) {
                   9641:         my (%counts,$max_match_format);
1.710     bisitz   9642:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9643:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9644:         my %idmap = &username_to_idmap($classlist);
                   9645:         foreach my $key (keys(%idmap)) {
                   9646:             my $lckey = lc($key);
                   9647:             $idmap{$lckey} = $idmap{$key};
                   9648:         }
                   9649:         my %unique_formats;
1.754     raeburn  9650:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9651:         foreach my $line (@formatlines) {
                   9652:             chomp($line);
                   9653:             my @config = split(/:/,$line);
                   9654:             my $idstart = $config[5];
                   9655:             my $idlength = $config[6];
                   9656:             if (($idstart ne '') && ($idlength > 0)) {
                   9657:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9658:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9659:                 } else {
                   9660:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9661:                 }
                   9662:             }
                   9663:         }
                   9664:         foreach my $key (keys(%unique_formats)) {
                   9665:             my ($idstart,$idlength) = split(':',$key);
                   9666:             %{$counts{$key}} = (
                   9667:                                'found'   => 0,
                   9668:                                'total'   => 0,
1.770     raeburn  9669:                                'totalanysec' => 0,
                   9670:                                'othersec' => 0,
1.567     raeburn  9671:                               );
                   9672:             foreach my $line (@lines) {
                   9673:                 next if ($line =~ /^#/);
                   9674:                 next if ($line =~ /^[\s\cz]*$/);
                   9675:                 my $id = substr($line,$idstart-1,$idlength);
                   9676:                 $id = lc($id);
                   9677:                 if (exists($idmap{$id})) {
1.770     raeburn  9678:                     if ($checksec ne '') {
                   9679:                         $counts{$key}{'totalanysec'} ++;
                   9680:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9681:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9682:                             if ($stusec ne $checksec) {
                   9683:                                 if (@possibles) {
                   9684:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9685:                                         $counts{$key}{'othersec'} ++;
                   9686:                                         next;
                   9687:                                     }
                   9688:                                 } else {
                   9689:                                     $counts{$key}{'othersec'} ++;
                   9690:                                     next;
                   9691:                                 }
                   9692:                             }
                   9693:                         }
                   9694:                     }
1.567     raeburn  9695:                     $counts{$key}{'found'} ++;
                   9696:                 }
                   9697:                 $counts{$key}{'total'} ++;
                   9698:             }
                   9699:             if ($counts{$key}{'total'}) {
                   9700:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9701:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9702:                     $max_match_pct = $percent_match;
                   9703:                     $max_match_format = $key;
1.710     bisitz   9704:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9705:                     $max_match_count = $counts{$key}{'total'};
                   9706:                 }
                   9707:             }
                   9708:         }
1.770     raeburn  9709:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9710:             my $format_descs;
                   9711:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9712:             for (my $i=0; $i<$numwithformat; $i++) {
                   9713:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9714:                 if ($i<$numwithformat-2) {
                   9715:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9716:                 } elsif ($i==$numwithformat-2) {
                   9717:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9718:                 } elsif ($i==$numwithformat-1) {
                   9719:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9720:                 }
                   9721:             }
                   9722:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9723:             $output .= '<br />';
                   9724:             if ($found_match_count == $max_match_count) {
                   9725:                 # 100% matching entries
                   9726:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9727:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9728:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9729:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9730:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9731:                     ' in the file (for the format defined for [_3]).',
                   9732:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9733:             } else {
                   9734:                 # Not all entries matching? -> Show warning and additional info
                   9735:                 $output .=
                   9736:                     &Apache::lonhtmlcommon::confirm_success(
                   9737:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9738:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9739:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9740:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9741:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9742:                         ' in the file (for the format defined for [_3]).',
                   9743:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9744:                     '<p class="LC_info">'.
                   9745:                     &mt('A low percentage of matches results from one of the following:').
                   9746:                     '</p><ul>'.
                   9747:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9748:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9749:                                '<i>'.$cdom.'</i>').'</li>'.
                   9750:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9751:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9752:                     '</ul>';
                   9753:             }
1.770     raeburn  9754:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9755:                 if ($counts{$max_match_format}{'othersec'}) {
                   9756:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9757:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9758:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9759:                     &js_escape(\$confirmdel);
                   9760:                     $output .= '<p class="LC_warning">'.
                   9761:                                &mt('Comparison of student IDs in the uploaded file with the course roster found [_1][quant,_2,match,matches][_3] for students in section(s) for which none of your role(s) have privileges to modify grades',
                   9762:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9763:                                '<br />'.
                   9764:                                &mt('Unless you are assigned role(s) which allow modification of grades in additional sections, [_1] of the records in this file will be automatically excluded when you perform bubblesheet grading.','<b>'.$showpct.'</b>').
                   9765:                                '</p><p>'.
                   9766:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9767:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9768:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9769:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9770:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9771:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9772:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9773:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9774:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9775:                                '</form></p>';
                   9776:                 }
                   9777:             }
1.567     raeburn  9778:         }
1.770     raeburn  9779:         if (($context eq 'download') && ($checksec ne '')) {
                   9780:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9781:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9782:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9783:             }
                   9784:         } 
                   9785:     } elsif ($context ne 'download') {
1.710     bisitz   9786:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9787:     }
                   9788:     return $output;
                   9789: }
                   9790: 
1.770     raeburn  9791: sub gradable_sections {
                   9792:     my $checksec = $env{'request.course.sec'};
                   9793:     my @oksecs;
                   9794:     if ($checksec) {
                   9795:         my %availablesecs = &sections_grade_privs();
                   9796:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9797:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9798:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9799:                     push(@oksecs,$sec);
                   9800:                 }
                   9801:             }
                   9802:             if (grep(/^all$/,@oksecs)) {
                   9803:                 undef($checksec);
                   9804:             }
                   9805:         }
                   9806:     }
                   9807:     return($checksec,@oksecs);
                   9808: }
                   9809: 
                   9810: sub sections_grade_privs {
                   9811:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9812:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9813:     my %availablesecs = (
                   9814:                           mgr => [],
                   9815:                           vgr => [],
                   9816:                           usc => [],
                   9817:                         );
                   9818:     my $ccrole = 'cc';
                   9819:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9820:         $ccrole = 'co';
                   9821:     }
                   9822:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9823:                                                      'userroles',['active'],
                   9824:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9825:     my $crsid = $cnum.':'.$cdom;
                   9826:     foreach my $item (keys(%crsroleshash)) {
                   9827:         next unless ($item =~ /^$crsid\:/);
                   9828:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9829:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9830:         if ($sec ne '') {
                   9831:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9832:         }
                   9833:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9834:             foreach my $priv ('mgr','vgr','usc') { 
                   9835:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9836:                     if ($sec eq '') {
                   9837:                         $availablesecs{$priv} = ['all'];
                   9838:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9839:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9840:                             push(@{$availablesecs{$priv}},$sec);
                   9841:                         }
                   9842:                     }
                   9843:                 }
                   9844:             }
                   9845:         } elsif ($role =~ m{^cr/}) {
                   9846:             foreach my $priv ('mgr','vgr','usc') {
                   9847:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9848:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9849:                         if ($sec eq '') {
                   9850:                             $availablesecs{$priv} = ['all'];
                   9851:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9852:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9853:                                 push(@{$availablesecs{$priv}},$sec);
                   9854:                             }
                   9855:                         }
                   9856:                     }
                   9857:                 }
                   9858:             }
                   9859:         }
                   9860:     }
                   9861:     return %availablesecs;
                   9862: }
                   9863: 
                   9864: sub scantron_upload_delete {
                   9865:     my ($r,$symb) = @_;
                   9866:     my $filename = $env{'form.uploadedfile'};
                   9867:     if ($filename =~ /^scantron_orig_/) {
                   9868:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9869:             &Apache::lonnet::allowed('usc',
                   9870:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9871:             &Apache::lonnet::allowed('usc',
                   9872:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9873:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9874:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9875:             if ($retrieval eq '-1') {
                   9876:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9877:                           &mt('File requested for deletion not found.'));
                   9878:             } else {
                   9879:                 $filename =~ s/^scantron_orig_//;
                   9880:                 if ($filename ne '') {
                   9881:                     my ($is_valid,$numleft);
                   9882:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9883:                     if (keys(%info)) {
                   9884:                         if (ref($info{$filename}) eq 'HASH') {
                   9885:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9886:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9887:                                     $is_valid = 1;
                   9888:                                     delete($info{$filename}{$timestamp}); 
                   9889:                                 }
                   9890:                             }
                   9891:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9892:                         }
                   9893:                     }
                   9894:                     if ($is_valid) {
                   9895:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9896:                         if ($result eq 'ok') {
                   9897:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9898:                             if ($numleft) {
                   9899:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9900:                             } else {
                   9901:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9902:                             }
                   9903:                         } else {
                   9904:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9905:                                       &mt('Result was [_1]',$result));
                   9906:                         }
                   9907:                     } else {
                   9908:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9909:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9910:                     }
                   9911:                 } else {
                   9912:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9913:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9914:                 }
                   9915:             }
                   9916:         } else {
                   9917:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9918:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9919:         }
                   9920:     } else {
                   9921:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9922:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9923:     }
                   9924:     return;
                   9925: }
                   9926: 
1.202     albertel 9927: sub valid_file {
                   9928:     my ($requested_file)=@_;
                   9929:     foreach my $filename (sort(&scantron_filenames())) {
                   9930: 	if ($requested_file eq $filename) { return 1; }
                   9931:     }
                   9932:     return 0;
                   9933: }
                   9934: 
                   9935: sub scantron_download_scantron_data {
1.767     raeburn  9936:     my ($r,$symb) = @_;
1.608     www      9937:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9938:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9939:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9940:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9941:     if (! &valid_file($file)) {
1.492     albertel 9942: 	$r->print('
1.202     albertel 9943: 	<p>
1.686     bisitz   9944: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9945:         </p>
1.492     albertel 9946: ');
1.202     albertel 9947: 	return;
                   9948:     }
1.770     raeburn  9949:     my (%uploader,$is_owner,%counts,$percent);
                   9950:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   9951:     if (ref($uploader{$file}) eq 'HASH') {
                   9952:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   9953:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9954:                 $is_owner = 1;
                   9955:                 last;
                   9956:             }
                   9957:         }
                   9958:     }
                   9959:     unless ($is_owner) {
                   9960:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   9961:         if ($counts{'totalanysec'}) {
                   9962:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   9963:             if ($percent_othersec >= 10) {
                   9964:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   9965:                 $r->print('<p class="LC_warning">'.
                   9966:                           &mt('The original uploaded file includes [_1] or more of records for students for which none of your roles have rights to modify grades, so files are unavailable for download.',$showpct).
                   9967:                           '</p>');
                   9968:                 return;
                   9969:             }
                   9970:         }
                   9971:     }
1.202     albertel 9972:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9973:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9974:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9975:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9976:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9977:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9978:     $r->print('
1.202     albertel 9979:     <p>
1.723     raeburn  9980: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9981: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9982:     </p>
                   9983:     <p>
1.492     albertel 9984: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9985: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9986:     </p>
                   9987:     <p>
1.492     albertel 9988: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9989: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9990:     </p>
1.492     albertel 9991: ');
1.202     albertel 9992:     return '';
                   9993: }
1.157     albertel 9994: 
1.523     raeburn  9995: sub checkscantron_results {
1.608     www      9996:     my ($r,$symb) = @_;
1.523     raeburn  9997:     if (!$symb) {return '';}
                   9998:     my $cid = $env{'request.course.id'};
1.755     raeburn  9999:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  10000:     my $numletts = scalar(keys(%lettdig));
                   10001:     my $cnum = $env{'course.'.$cid.'.num'};
                   10002:     my $cdom = $env{'course.'.$cid.'.domain'};
                   10003:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   10004:     my %record;
                   10005:     my %scantron_config =
1.754     raeburn  10006:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  10007:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  10008:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  10009:     my $classlist=&Apache::loncoursedata::get_classlist();
                   10010:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   10011:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  10012:     unless (ref($navmap)) {
                   10013:         $r->print(&navmap_errormsg());
                   10014:         return '';
                   10015:     }
1.523     raeburn  10016:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  10017:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   10018:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  10019:     if (ref($map)) { 
                   10020:         $randomorder=$map->randomorder();
1.689     raeburn  10021:         $randompick=$map->randompick();
1.677     raeburn  10022:     }
1.557     raeburn  10023:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  10024:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   10025:     if ($nav_error) {
                   10026:         $r->print(&navmap_errormsg());
                   10027:         return '';
1.678     raeburn  10028:     }
1.673     raeburn  10029:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   10030:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  10031:     my ($uname,$udom);
1.523     raeburn  10032:     my (%scandata,%lastname,%bylast);
                   10033:     $r->print('
                   10034: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   10035: 
                   10036:     my @delayqueue;
                   10037:     my %completedstudents;
                   10038: 
1.691     raeburn  10039:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      10040:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  10041:     my ($username,$domain,$started);
1.649     raeburn  10042:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  10043:     if ($nav_error) {
                   10044:         $r->print(&navmap_errormsg());
                   10045:         return '';
                   10046:     }
1.523     raeburn  10047: 
1.667     www      10048:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  10049:     my $start=&Time::HiRes::time();
                   10050:     my $i=-1;
                   10051: 
                   10052:     while ($i<$scanlines->{'count'}) {
                   10053:         ($username,$domain,$uname)=('','','');
                   10054:         $i++;
                   10055:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   10056:         if ($line=~/^[\s\cz]*$/) { next; }
                   10057:         if ($started) {
1.667     www      10058:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  10059:         }
                   10060:         $started=1;
                   10061:         my $scan_record=
                   10062:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   10063:                                                      $scan_data);
1.693     raeburn  10064:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   10065:                                               \%idmap,$i)) {
1.523     raeburn  10066:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10067:                                 'Unable to find a student that matches',1);
                   10068:             next;
                   10069:         }
                   10070:         if (exists $completedstudents{$uname}) {
                   10071:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   10072:                                 'Student '.$uname.' has multiple sheets',2);
                   10073:             next;
                   10074:         }
                   10075:         my $pid = $scan_record->{'scantron.ID'};
                   10076:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   10077:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  10078:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   10079:         my $user = $uname.':'.$usec;
1.523     raeburn  10080:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  10081: 
1.678     raeburn  10082:         my $scancode;
1.677     raeburn  10083:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   10084:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   10085:             $scancode = $scan_record->{'scantron.CODE'};
                   10086:         } else {
                   10087:             $scancode = '';
                   10088:         }
                   10089: 
                   10090:         my @mapresources = @resources;
1.691     raeburn  10091:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   10092:         my %respnumlookup=();
                   10093:         my %startline=();
1.689     raeburn  10094:         if ($randomorder || $randompick) {
1.678     raeburn  10095:             @mapresources =
1.691     raeburn  10096:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   10097:                              \%orderedforcode);
                   10098:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   10099:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   10100:                                              \%grader_partids_by_symb,\%orderedforcode,
                   10101:                                              \%respnumlookup,\%startline);
                   10102:             if ($randompick && $total) {
                   10103:                 $lastpos = $total*$scantron_config{'Qlength'};
                   10104:             }
1.677     raeburn  10105:         }
1.691     raeburn  10106:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   10107:         chomp($scandata{$pid});
                   10108:         $scandata{$pid} =~ s/\r$//;
                   10109: 
1.523     raeburn  10110:         my $counter = -1;
1.677     raeburn  10111:         foreach my $resource (@mapresources) {
1.557     raeburn  10112:             my $parts;
1.554     raeburn  10113:             my $ressymb = $resource->symb();
1.557     raeburn  10114:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   10115:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  10116:                 my $currcode;
                   10117:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   10118:                     $currcode = $scancode;
                   10119:                 }
1.557     raeburn  10120:                 (my $analysis,$parts) =
1.672     raeburn  10121:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   10122:                                               $username,$domain,undef,
1.741     raeburn  10123:                                               $bubbles_per_row,$currcode);
1.557     raeburn  10124:             } else {
                   10125:                 $parts = $grader_partids_by_symb{$ressymb};
                   10126:             }
1.542     raeburn  10127:             ($counter,my $recording) =
                   10128:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  10129:                                          $scandata{$pid},$parts,
1.691     raeburn  10130:                                          \%scantron_config,\%lettdig,$numletts,
                   10131:                                          $randomorder,$randompick,
                   10132:                                          \%respnumlookup,\%startline);
1.542     raeburn  10133:             $record{$pid} .= $recording;
1.523     raeburn  10134:         }
                   10135:     }
                   10136:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   10137:     $r->print('<br />');
                   10138:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   10139:     $passed = 0;
                   10140:     $failed = 0;
                   10141:     $numstudents = 0;
                   10142:     foreach my $last (sort(keys(%bylast))) {
                   10143:         if (ref($bylast{$last}) eq 'ARRAY') {
                   10144:             foreach my $pid (sort(@{$bylast{$last}})) {
                   10145:                 my $showscandata = $scandata{$pid};
                   10146:                 my $showrecord = $record{$pid};
                   10147:                 $showscandata =~ s/\s/&nbsp;/g;
                   10148:                 $showrecord =~ s/\s/&nbsp;/g;
                   10149:                 if ($scandata{$pid} eq $record{$pid}) {
                   10150:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   10151:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      10152: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  10153: '</tr>'."\n".
                   10154: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10155: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  10156:                     $passed ++;
                   10157:                 } else {
                   10158:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10159:                     $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  10160: '</tr>'."\n".
                   10161: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10162: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10163: '</tr>'."\n";
                   10164:                     $failed ++;
                   10165:                 }
                   10166:                 $numstudents ++;
                   10167:             }
                   10168:         }
                   10169:     }
1.648     bisitz   10170:     $r->print(
                   10171:         '<p>'
                   10172:        .&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).',
                   10173:             '<b>',
                   10174:             $numstudents,
                   10175:             '</b>',
                   10176:             $env{'form.scantron_maxbubble'})
                   10177:        .'</p>'
                   10178:     );
1.682     raeburn  10179:     $r->print('<p>'
1.683     raeburn  10180:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10181:              .'<br />'
                   10182:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10183:              .'</p>'
                   10184:     );
1.523     raeburn  10185:     if ($passed) {
1.572     www      10186:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10187:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10188:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10189:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10190:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10191:                  $okstudents."\n".
                   10192:                  &Apache::loncommon::end_data_table().'<br />');
                   10193:     }
                   10194:     if ($failed) {
1.572     www      10195:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10196:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10197:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10198:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10199:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10200:                  $badstudents."\n".
                   10201:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10202:                  &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  10203:     }
1.614     www      10204:     $r->print('</form><br />');
1.523     raeburn  10205:     return;
                   10206: }
                   10207: 
1.542     raeburn  10208: sub verify_scantron_grading {
1.554     raeburn  10209:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10210:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10211:         $respnumlookup,$startline) = @_;
1.542     raeburn  10212:     my ($record,%expected,%startpos);
                   10213:     return ($counter,$record) if (!ref($resource));
                   10214:     return ($counter,$record) if (!$resource->is_problem());
                   10215:     my $symb = $resource->symb();
1.554     raeburn  10216:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10217:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10218:         $counter ++;
                   10219:         $expected{$part_id} = 0;
1.691     raeburn  10220:         my $respnum = $counter;
                   10221:         if ($randomorder || $randompick) {
                   10222:             $respnum = $respnumlookup->{$counter};
                   10223:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10224:         } else {
                   10225:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10226:         }
                   10227:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10228:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10229:             foreach my $item (@sub_lines) {
                   10230:                 $expected{$part_id} += $item;
                   10231:             }
                   10232:         } else {
1.691     raeburn  10233:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10234:         }
                   10235:     }
                   10236:     if ($symb) {
                   10237:         my %recorded;
                   10238:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10239:         if ($returnhash{'version'}) {
                   10240:             my %lasthash=();
                   10241:             my $version;
                   10242:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10243:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10244:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10245:                 }
                   10246:             }
                   10247:             foreach my $key (keys(%lasthash)) {
                   10248:                 if ($key =~ /\.scantron$/) {
                   10249:                     my $value = &unescape($lasthash{$key});
                   10250:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10251:                     if ($value eq '') {
                   10252:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10253:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10254:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10255:                             }
                   10256:                         }
                   10257:                     } else {
                   10258:                         my @tocheck;
                   10259:                         my @items = split(//,$value);
                   10260:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10261:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10262:                             if (@items < $expected{$part_id}) {
                   10263:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10264:                                 my @singles = split(//,$fragment);
                   10265:                                 foreach my $pos (@singles) {
                   10266:                                     if ($pos eq ' ') {
                   10267:                                         push(@tocheck,$pos);
                   10268:                                     } else {
                   10269:                                         my $next = shift(@items);
                   10270:                                         push(@tocheck,$next);
                   10271:                                     }
                   10272:                                 }
                   10273:                             } else {
                   10274:                                 @tocheck = @items;
                   10275:                             }
                   10276:                             foreach my $letter (@tocheck) {
                   10277:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10278:                                     if ($letter !~ /^[A-J]$/) {
                   10279:                                         $letter = $scantron_config->{'Qoff'};
                   10280:                                     }
                   10281:                                     $recorded{$part_id} .= $letter;
                   10282:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10283:                                     my $digit;
                   10284:                                     if ($letter !~ /^[A-J]$/) {
                   10285:                                         $digit = $scantron_config->{'Qoff'};
                   10286:                                     } else {
                   10287:                                         $digit = $lettdig->{$letter};
                   10288:                                     }
                   10289:                                     $recorded{$part_id} .= $digit;
                   10290:                                 }
                   10291:                             }
                   10292:                         } else {
                   10293:                             @tocheck = @items;
                   10294:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10295:                                 my $curr_sub = shift(@tocheck);
                   10296:                                 my $digit;
                   10297:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10298:                                     $digit = $lettdig->{$curr_sub}-1;
                   10299:                                 }
                   10300:                                 if ($curr_sub eq 'J') {
                   10301:                                     $digit += scalar($numletts);
                   10302:                                 }
                   10303:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10304:                                     if ($j == $digit) {
                   10305:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10306:                                     } else {
                   10307:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10308:                                     }
                   10309:                                 }
                   10310:                             }
                   10311:                         }
                   10312:                     }
                   10313:                 }
                   10314:             }
                   10315:         }
1.554     raeburn  10316:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10317:             if ($recorded{$part_id} eq '') {
                   10318:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10319:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10320:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10321:                     }
                   10322:                 }
                   10323:             }
                   10324:             $record .= $recorded{$part_id};
                   10325:         }
                   10326:     }
                   10327:     return ($counter,$record);
                   10328: }
                   10329: 
1.75      albertel 10330: #-------- end of section for handling grading scantron forms -------
                   10331: #
                   10332: #-------------------------------------------------------------------
                   10333: 
1.72      ng       10334: #-------------------------- Menu interface -------------------------
                   10335: #
1.614     www      10336: #--- Href with symb and command ---
                   10337: 
                   10338: sub href_symb_cmd {
                   10339:     my ($symb,$cmd)=@_;
1.669     raeburn  10340:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10341: }
                   10342: 
1.443     banghart 10343: sub grading_menu {
1.608     www      10344:     my ($request,$symb) = @_;
1.443     banghart 10345:     if (!$symb) {return '';}
                   10346: 
                   10347:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10348:                   'command'=>'individual');
1.538     schulted 10349:     
1.598     www      10350:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10351: 
                   10352:     $fields{'command'}='ungraded';
                   10353:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10354: 
                   10355:     $fields{'command'}='table';
                   10356:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10357: 
                   10358:     $fields{'command'}='all_for_one';
                   10359:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10360: 
1.621     www      10361:     $fields{'command'}='downloadfilesselect';
                   10362:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10363: 
1.443     banghart 10364:     $fields{'command'} = 'csvform';
1.538     schulted 10365:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10366:     
1.443     banghart 10367:     $fields{'command'} = 'processclicker';
1.538     schulted 10368:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10369:     
1.443     banghart 10370:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10371:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10372: 
                   10373:     $fields{'command'} = 'initialverifyreceipt';
                   10374:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10375:     
1.598     www      10376:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10377:             items =>[
1.598     www      10378:                         {	linktext => 'Select individual students to grade',
                   10379:                     		url => $url1a,
1.538     schulted 10380:                     		permission => 'F',
1.636     wenzelju 10381:                     		icon => 'grade_students.png',
1.598     www      10382:                     		linktitle => 'Grade current resource for a selection of students.'
                   10383:                         }, 
1.764     raeburn  10384:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10385:                                 url => $url1b,
                   10386:                                 permission => 'F',
1.636     wenzelju 10387:                                 icon => 'ungrade_sub.png',
1.598     www      10388:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10389:                         },
1.598     www      10390: 
                   10391:                         {       linktext => 'Grading table',
                   10392:                                 url => $url1c,
                   10393:                                 permission => 'F',
1.636     wenzelju 10394:                                 icon => 'grading_table.png',
1.598     www      10395:                                 linktitle => 'Grade current resource for all students.'
                   10396:                         },
1.615     www      10397:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10398:                                 url => $url1d,
                   10399:                                 permission => 'F',
1.636     wenzelju 10400:                                 icon => 'grade_PageFolder.png',
1.598     www      10401:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10402:                         },
                   10403:                         {       linktext => 'Download submissions',
                   10404:                                 url => $url1e,
                   10405:                                 permission => 'F',
1.636     wenzelju 10406:                                 icon => 'download_sub.png',
1.621     www      10407:                                 linktitle => 'Download all students submissions.'
1.598     www      10408:                         }]},
                   10409:                          { categorytitle=>'Automated Grading',
                   10410:                items =>[
                   10411: 
1.538     schulted 10412:                 	    {	linktext => 'Upload Scores',
                   10413:                     		url => $url2,
                   10414:                     		permission => 'F',
                   10415:                     		icon => 'uploadscores.png',
                   10416:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10417:                 	    },
                   10418:                 	    {	linktext => 'Process Clicker',
                   10419:                     		url => $url3,
                   10420:                     		permission => 'F',
                   10421:                     		icon => 'addClickerInfoFile.png',
                   10422:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10423:                 	    },
1.587     raeburn  10424:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10425:                     		url => $url4,
                   10426:                     		permission => 'F',
1.636     wenzelju 10427:                     		icon => 'bubblesheet.png',
1.648     bisitz   10428:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10429:                 	    },
1.616     www      10430:                             {   linktext => 'Verify Receipt Number',
1.602     www      10431:                                 url => $url5,
                   10432:                                 permission => 'F',
1.636     wenzelju 10433:                                 icon => 'receipt_number.png',
1.602     www      10434:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10435:                             }
                   10436: 
1.538     schulted 10437:                     ]
                   10438:             });
                   10439: 
1.443     banghart 10440:     # Create the menu
                   10441:     my $Str;
1.445     banghart 10442:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10443:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10444:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10445: 
1.602     www      10446:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10447:     return $Str;    
                   10448: }
                   10449: 
1.598     www      10450: sub ungraded {
                   10451:     my ($request)=@_;
                   10452:     &submit_options($request);
                   10453: }
                   10454: 
1.599     www      10455: sub submit_options_sequence {
1.608     www      10456:     my ($request,$symb) = @_;
1.599     www      10457:     if (!$symb) {return '';}
1.600     www      10458:     &commonJSfunctions($request);
                   10459:     my $result;
1.599     www      10460: 
1.600     www      10461:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10462:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10463:     $result.=&selectfield(0).
1.601     www      10464:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10465:             <div>
                   10466:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10467:             </div>
                   10468:         </div>
                   10469:   </form>';
                   10470:     return $result;
                   10471: }
                   10472: 
                   10473: sub submit_options_table {
1.608     www      10474:     my ($request,$symb) = @_;
1.600     www      10475:     if (!$symb) {return '';}
1.599     www      10476:     &commonJSfunctions($request);
1.746     raeburn  10477:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10478:     my $result;
                   10479: 
                   10480:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10481:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10482: 
1.745     raeburn  10483:     $result.=&selectfield(1,$is_tool).
1.601     www      10484:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10485:             <div>
                   10486:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10487:             </div>
                   10488:         </div>
                   10489:   </form>';
                   10490:     return $result;
                   10491: }
1.443     banghart 10492: 
1.621     www      10493: sub submit_options_download {
                   10494:     my ($request,$symb) = @_;
                   10495:     if (!$symb) {return '';}
                   10496: 
1.773   ! raeburn  10497:     my $res_error;
        !          10498:     my ($partlist,$handgrade,$responseType,$numresp,$numessay,$numdropbox) =
        !          10499:         &response_type($symb,\$res_error);
        !          10500:     if ($res_error) {
        !          10501:         $request->print(&mt('An error occurred retrieving response types'));
        !          10502:         return;
        !          10503:     }
        !          10504:     unless ($numessay) {
        !          10505:         $request->print(&mt('No essayresponse items found'));
        !          10506:         return;
        !          10507:     }
        !          10508:     my $table;
        !          10509:     if (ref($partlist) eq 'ARRAY') {
        !          10510:         if (scalar(@$partlist) > 1 ) {
        !          10511:             $table = &showResourceInfo($symb,$partlist,$responseType,'gradingMenu',1,1);
        !          10512:         }
        !          10513:     }
        !          10514: 
1.746     raeburn  10515:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10516:     &commonJSfunctions($request);
                   10517: 
                   10518:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.773   ! raeburn  10519:                $table."\n".
        !          10520:                '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.621     www      10521:     $result.='
                   10522: <h2>
1.750     raeburn  10523:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10524: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10525:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10526:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10527:             </div>
                   10528:           </div>
1.600     www      10529: 
                   10530: 
1.621     www      10531:   </form>';
                   10532:     return $result;
                   10533: }
                   10534: 
1.443     banghart 10535: #--- Displays the submissions first page -------
                   10536: sub submit_options {
1.608     www      10537:     my ($request,$symb) = @_;
1.72      ng       10538:     if (!$symb) {return '';}
                   10539: 
1.746     raeburn  10540:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10541:     &commonJSfunctions($request);
1.473     albertel 10542:     my $result;
1.533     bisitz   10543: 
1.72      ng       10544:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10545: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10546:     $result.=&selectfield(1,$is_tool).'
1.601     www      10547:                 <input type="hidden" name="command" value="submission" /> 
                   10548: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10549:             </div>
                   10550:           </div>
                   10551:   </form>';
                   10552:     return $result;
                   10553: }
1.533     bisitz   10554: 
1.601     www      10555: sub selectfield {
1.745     raeburn  10556:    my ($full,$is_tool)=@_;
                   10557:    my %options;
                   10558:    if ($is_tool) {
                   10559:        %options =
                   10560:            (&transtatus_options,
                   10561:             'select_form_order' => ['yes','incorrect','all']);
                   10562:    } else {
                   10563:        %options = 
                   10564:            (&substatus_options,
                   10565:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10566:    }
1.601     www      10567:    my $result='<div class="LC_columnSection">
1.537     harmsja  10568:   
1.533     bisitz   10569:     <fieldset>
                   10570:       <legend>
                   10571:        '.&mt('Sections').'
                   10572:       </legend>
1.601     www      10573:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10574:     </fieldset>
1.537     harmsja  10575:   
1.533     bisitz   10576:     <fieldset>
                   10577:       <legend>
                   10578:         '.&mt('Groups').'
                   10579:       </legend>
                   10580:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10581:     </fieldset>
1.537     harmsja  10582:   
1.533     bisitz   10583:     <fieldset>
                   10584:       <legend>
                   10585:         '.&mt('Access Status').'
                   10586:       </legend>
1.601     www      10587:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10588:     </fieldset>';
                   10589:     if ($full) {
1.745     raeburn  10590:         my $heading = &mt('Submission Status');
                   10591:         if ($is_tool) {
                   10592:             $heading = &mt('Transaction Status');
                   10593:         }
                   10594:         $result.='
1.533     bisitz   10595:     <fieldset>
                   10596:       <legend>
1.745     raeburn  10597:         '.$heading.'
1.601     www      10598:       </legend>'.
1.635     raeburn  10599:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10600:    '</fieldset>';
                   10601:     }
                   10602:     $result.='</div><br />';
1.44      ng       10603:     return $result;
1.2       albertel 10604: }
                   10605: 
1.738     raeburn  10606: sub substatus_options {
                   10607:     return &Apache::lonlocal::texthash(
                   10608:                                       'yes'       => 'with submissions',
                   10609:                                       'queued'    => 'in grading queue',
                   10610:                                       'graded'    => 'with ungraded submissions',
                   10611:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10612:                                       'all'       => 'with any status',
                   10613:                                       );
1.738     raeburn  10614: }
                   10615: 
1.745     raeburn  10616: sub transtatus_options {
                   10617:     return &Apache::lonlocal::texthash(
                   10618:                                        'yes'       => 'with score transactions',
                   10619:                                        'incorrect' => 'with less than full credit',
                   10620:                                        'all'       => 'with any status',
                   10621:                                       );
                   10622: }
                   10623: 
1.285     albertel 10624: sub reset_perm {
                   10625:     undef(%perm);
                   10626: }
                   10627: 
                   10628: sub init_perm {
                   10629:     &reset_perm();
1.770     raeburn  10630:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10631: 
                   10632: 	my $scope = $env{'request.course.id'};
                   10633: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10634: 
                   10635: 	    $scope .= '/'.$env{'request.course.sec'};
                   10636: 	    if ( $perm{$test_perm}=
                   10637: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10638: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10639: 	    } else {
                   10640: 		delete($perm{$test_perm});
                   10641: 	    }
1.285     albertel 10642: 	}
                   10643:     }
                   10644: }
                   10645: 
1.674     raeburn  10646: sub init_old_essays {
                   10647:     my ($symb,$apath,$adom,$aname) = @_;
                   10648:     if ($symb ne '') {
                   10649:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10650:         if (keys(%essays) > 0) {
                   10651:             $old_essays{$symb} = \%essays;
                   10652:         }
                   10653:     }
                   10654:     return;
                   10655: }
                   10656: 
                   10657: sub reset_old_essays {
                   10658:     undef(%old_essays);
                   10659: }
                   10660: 
1.400     www      10661: sub gather_clicker_ids {
1.408     albertel 10662:     my %clicker_ids;
1.400     www      10663: 
                   10664:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10665: 
                   10666:     # Set up a couple variables.
1.407     albertel 10667:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10668:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10669:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10670: 
1.407     albertel 10671:     foreach my $student (keys(%$classlist)) {
1.438     www      10672:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10673:         my $username = $classlist->{$student}->[$username_idx];
                   10674:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10675:         my $clickers =
1.408     albertel 10676: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10677:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10678:             $id=~s/^[\#0]+//;
1.421     www      10679:             $id=~s/[\-\:]//g;
1.407     albertel 10680:             if (exists($clicker_ids{$id})) {
1.408     albertel 10681: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10682:             } else {
1.408     albertel 10683: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10684:             }
                   10685:         }
                   10686:     }
1.407     albertel 10687:     return %clicker_ids;
1.400     www      10688: }
                   10689: 
1.402     www      10690: sub gather_adv_clicker_ids {
1.408     albertel 10691:     my %clicker_ids;
1.402     www      10692:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10693:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10694:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10695:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10696:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10697:             my ($puname,$pudom)=split(/\:/,$person);
                   10698:             my $clickers =
1.408     albertel 10699: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10700:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10701: 		$id=~s/^[\#0]+//;
1.421     www      10702:                 $id=~s/[\-\:]//g;
1.408     albertel 10703: 		if (exists($clicker_ids{$id})) {
                   10704: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10705: 		} else {
                   10706: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10707: 		}
1.405     www      10708:             }
1.402     www      10709:         }
                   10710:     }
1.407     albertel 10711:     return %clicker_ids;
1.402     www      10712: }
                   10713: 
1.413     www      10714: sub clicker_grading_parameters {
                   10715:     return ('gradingmechanism' => 'scalar',
                   10716:             'upfiletype' => 'scalar',
                   10717:             'specificid' => 'scalar',
                   10718:             'pcorrect' => 'scalar',
                   10719:             'pincorrect' => 'scalar');
                   10720: }
                   10721: 
1.400     www      10722: sub process_clicker {
1.608     www      10723:     my ($r,$symb)=@_;
1.400     www      10724:     if (!$symb) {return '';}
                   10725:     my $result=&checkforfile_js();
1.632     www      10726:     $result.=&Apache::loncommon::start_data_table().
                   10727:              &Apache::loncommon::start_data_table_header_row().
                   10728:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10729:              &Apache::loncommon::end_data_table_header_row().
                   10730:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10731: # Attempt to restore parameters from last session, set defaults if not present
                   10732:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10733:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10734:                                                  \%Saveable_Parameters);
                   10735:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10736:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10737:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10738:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10739: 
                   10740:     my %checked;
1.521     www      10741:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10742:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10743:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10744:        }
                   10745:     }
                   10746: 
1.632     www      10747:     my $upload=&mt("Evaluate File");
1.400     www      10748:     my $type=&mt("Type");
1.402     www      10749:     my $attendance=&mt("Award points just for participation");
                   10750:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10751:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10752:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10753:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10754:     my $pcorrect=&mt("Percentage points for correct solution");
                   10755:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10756:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10757: 						   {'iclicker' => 'i>clicker',
1.666     www      10758:                                                     'interwrite' => 'interwrite PRS',
                   10759:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10760:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10761:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10762: function sanitycheck() {
                   10763: // Accept only integer percentages
                   10764:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10765:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10766: // Find out grading choice
                   10767:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10768:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10769:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10770:       }
                   10771:    }
                   10772: // By default, new choice equals user selection
                   10773:    newgradingchoice=gradingchoice;
                   10774: // Not good to give more points for false answers than correct ones
                   10775:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10776:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10777:    }
                   10778: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10779:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10780:       document.forms.gradesupload.pcorrect.value=100;
                   10781:       document.forms.gradesupload.pincorrect.value=100;
                   10782:    }
                   10783: // If the values are different, cannot be attendance only
                   10784:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10785:        (gradingchoice=='attendance')) {
                   10786:        newgradingchoice='personnel';
                   10787:    }
                   10788: // Change grading choice to new one
                   10789:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10790:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10791:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10792:       } else {
                   10793:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10794:       }
                   10795:    }
                   10796: // Remember the old state
                   10797:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10798: }
1.597     wenzelju 10799: ENDUPFORM
                   10800:     $result.= <<ENDUPFORM;
1.400     www      10801: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10802: <input type="hidden" name="symb" value="$symb" />
                   10803: <input type="hidden" name="command" value="processclickerfile" />
                   10804: <input type="file" name="upfile" size="50" />
                   10805: <br /><label>$type: $selectform</label>
1.632     www      10806: ENDUPFORM
                   10807:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10808:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10809:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10810: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10811: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10812: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10813: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10814: <br />&nbsp;&nbsp;&nbsp;
                   10815: <input type="text" name="givenanswer" size="50" />
1.413     www      10816: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10817: ENDGRADINGFORM
1.766     raeburn  10818:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10819:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10820:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10821: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10822: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10823: </form>
1.632     www      10824: ENDPERCFORM
                   10825:     $result.='</td>'.
                   10826:              &Apache::loncommon::end_data_table_row().
                   10827:              &Apache::loncommon::end_data_table();
1.400     www      10828:     return $result;
                   10829: }
                   10830: 
                   10831: sub process_clicker_file {
1.766     raeburn  10832:     my ($r,$symb) = @_;
1.400     www      10833:     if (!$symb) {return '';}
1.413     www      10834: 
                   10835:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10836:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10837:                                               \%Saveable_Parameters);
1.598     www      10838:     my $result='';
1.404     www      10839:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10840: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10841: 	return $result;
1.404     www      10842:     }
1.522     www      10843:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10844:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10845:         return $result;
1.521     www      10846:     }
1.522     www      10847:     my $foundgiven=0;
1.521     www      10848:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10849:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10850:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10851:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10852:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10853:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10854:         $foundgiven=$#answers+1;
1.521     www      10855:     }
1.407     albertel 10856:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10857:     my %correct_ids;
1.404     www      10858:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10859: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10860:     }
                   10861:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10862: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10863: 	   $correct_id=~tr/a-z/A-Z/;
                   10864: 	   $correct_id=~s/\s//gs;
                   10865: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10866:            $correct_id=~s/[\-\:]//g;
1.414     www      10867:            if ($correct_id) {
                   10868: 	      $correct_ids{$correct_id}='specified';
                   10869:            }
                   10870:         }
1.400     www      10871:     }
1.404     www      10872:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10873: 	$result.=&mt('Score based on attendance only');
1.521     www      10874:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10875:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10876:     } else {
1.408     albertel 10877: 	my $number=0;
1.411     www      10878: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10879: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10880: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10881: 	    if ($correct_ids{$id} eq 'specified') {
                   10882: 		$result.=&mt('specified');
                   10883: 	    } else {
                   10884: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10885: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10886: 	    }
                   10887: 	    $number++;
                   10888: 	}
1.411     www      10889:         $result.="</p>\n";
1.710     bisitz   10890:         if ($number==0) {
                   10891:             $result .=
                   10892:                  &Apache::lonhtmlcommon::confirm_success(
                   10893:                      &mt('No IDs found to determine correct answer'),1);
                   10894:             return $result;
                   10895:         }
1.404     www      10896:     }
1.405     www      10897:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10898:         $result .=
                   10899:             &Apache::lonhtmlcommon::confirm_success(
                   10900:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10901:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10902:         return $result;
1.405     www      10903:     }
1.760     raeburn  10904:     my $mimetype;
                   10905:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10906:         my $mm = new File::MMagic;
                   10907:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10908:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10909:             $result.= '<p>'.
                   10910:                 &Apache::lonhtmlcommon::confirm_success(
                   10911:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10912:             return $result;
                   10913:         }
                   10914:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10915:         $result .= '<p>'.
                   10916:             &Apache::lonhtmlcommon::confirm_success(
                   10917:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10918:         return $result;
                   10919:     }
1.410     www      10920: 
                   10921: # Were able to get all the info needed, now analyze the file
                   10922: 
1.411     www      10923:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10924:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10925:     $result.=&Apache::loncommon::start_data_table().
                   10926:              &Apache::loncommon::start_data_table_header_row().
                   10927:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10928:              &Apache::loncommon::end_data_table_header_row().
                   10929:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10930: <td>
1.410     www      10931: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10932: <input type="hidden" name="symb" value="$symb" />
                   10933: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10934: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10935: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10936: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10937: ENDHEADER
1.522     www      10938:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10939:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10940:     } 
1.408     albertel 10941:     my %responses;
                   10942:     my @questiontitles;
1.405     www      10943:     my $errormsg='';
                   10944:     my $number=0;
                   10945:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10946:         if ($mimetype eq 'text/plain') {
                   10947:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10948:         } elsif ($mimetype eq 'text/html') {
                   10949:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10950:         }
                   10951:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10952:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10953:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10954:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10955:     }
1.411     www      10956:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10957:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10958:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10959:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10960:              '<br />';
1.522     www      10961:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10962:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10963:        return $result;
1.522     www      10964:     } 
1.414     www      10965: # Remember Question Titles
                   10966: # FIXME: Possibly need delimiter other than ":"
                   10967:     for (my $i=0;$i<$number;$i++) {
                   10968:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10969:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10970:     }
1.411     www      10971:     my $correct_count=0;
                   10972:     my $student_count=0;
                   10973:     my $unknown_count=0;
1.414     www      10974: # Match answers with usernames
                   10975: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10976:     foreach my $id (keys(%responses)) {
1.410     www      10977:        if ($correct_ids{$id}) {
1.414     www      10978:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10979:           $correct_count++;
1.410     www      10980:        } elsif ($clicker_ids{$id}) {
1.437     www      10981:           if ($clicker_ids{$id}=~/\,/) {
                   10982: # More than one user with the same clicker!
1.632     www      10983:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10984:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10985:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10986:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10987:                            "<select name='multi".$id."'>";
                   10988:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10989:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10990:              }
                   10991:              $result.='</select>';
                   10992:              $unknown_count++;
                   10993:           } else {
                   10994: # Good: found one and only one user with the right clicker
                   10995:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10996:              $student_count++;
                   10997:           }
1.410     www      10998:        } else {
1.632     www      10999:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   11000:                            &Apache::loncommon::start_data_table_row()."<td>".
                   11001:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      11002:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   11003:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   11004:                    "\n".&mt("Domain").": ".
                   11005:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  11006:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      11007:           $unknown_count++;
1.410     www      11008:        }
1.405     www      11009:     }
1.412     www      11010:     $result.='<hr />'.
                   11011:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      11012:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      11013:        if ($correct_count==0) {
1.696     bisitz   11014:           $errormsg.="Found no correct answers for grading!";
1.412     www      11015:        } elsif ($correct_count>1) {
1.414     www      11016:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      11017:        }
                   11018:     }
1.428     www      11019:     if ($number<1) {
                   11020:        $errormsg.="Found no questions.";
                   11021:     }
1.412     www      11022:     if ($errormsg) {
                   11023:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   11024:     } else {
                   11025:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   11026:     }
1.632     www      11027:     $result.='</form></td>'.
                   11028:              &Apache::loncommon::end_data_table_row().
                   11029:              &Apache::loncommon::end_data_table();
1.614     www      11030:     return $result;
1.400     www      11031: }
                   11032: 
1.405     www      11033: sub iclicker_eval {
1.406     www      11034:     my ($questiontitles,$responses)=@_;
1.405     www      11035:     my $number=0;
                   11036:     my $errormsg='';
                   11037:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      11038:         my %components=&Apache::loncommon::record_sep($line);
                   11039:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 11040: 	if ($entries[0] eq 'Question') {
                   11041: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   11042: 		$$questiontitles[$number]=$entries[$i];
                   11043: 		$number++;
                   11044: 	    }
                   11045: 	}
                   11046: 	if ($entries[0]=~/^\#/) {
                   11047: 	    my $id=$entries[0];
                   11048: 	    my @idresponses;
                   11049: 	    $id=~s/^[\#0]+//;
                   11050: 	    for (my $i=0;$i<$number;$i++) {
                   11051: 		my $idx=3+$i*6;
1.644     www      11052:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 11053: 		push(@idresponses,$entries[$idx]);
                   11054: 	    }
                   11055: 	    $$responses{$id}=join(',',@idresponses);
                   11056: 	}
1.405     www      11057:     }
                   11058:     return ($errormsg,$number);
                   11059: }
                   11060: 
1.760     raeburn  11061: sub iclickerxml_eval {
                   11062:     my ($questiontitles,$responses)=@_;
                   11063:     my $number=0;
                   11064:     my $errormsg='';
                   11065:     my @state;
                   11066:     my %respbyid;
                   11067:     my $p = HTML::Parser->new
                   11068:     (
                   11069:         xml_mode => 1,
                   11070:         start_h =>
                   11071:             [sub {
                   11072:                  my ($tagname,$attr) = @_;
                   11073:                  push(@state,$tagname);
                   11074:                  if ("@state" eq "ssn p") {
                   11075:                      my $title = $attr->{qn};
                   11076:                      $title =~ s/(^\s+|\s+$)//g;
                   11077:                      $questiontitles->[$number]=$title;
                   11078:                  } elsif ("@state" eq "ssn p v") {
                   11079:                      my $id = $attr->{id};
                   11080:                      my $entry = $attr->{ans};
                   11081:                      $id=~s/^[\#0]+//;
                   11082:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   11083:                      $respbyid{$id}[$number] = $entry;
                   11084:                  }
                   11085:             }, "tagname, attr"],
                   11086:          end_h =>
                   11087:                [sub {
                   11088:                    my ($tagname) = @_;
                   11089:                    if ("@state" eq "ssn p") {
                   11090:                        $number++;
                   11091:                    }
                   11092:                    pop(@state);
                   11093:                 }, "tagname"],
                   11094:     );
                   11095: 
                   11096:     $p->parse($env{'form.upfile'});
                   11097:     $p->eof;
                   11098:     foreach my $id (keys(%respbyid)) {
                   11099:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   11100:     }
                   11101:     return ($errormsg,$number);
                   11102: }
                   11103: 
1.419     www      11104: sub interwrite_eval {
                   11105:     my ($questiontitles,$responses)=@_;
                   11106:     my $number=0;
                   11107:     my $errormsg='';
1.420     www      11108:     my $skipline=1;
                   11109:     my $questionnumber=0;
                   11110:     my %idresponses=();
1.419     www      11111:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11112:         my %components=&Apache::loncommon::record_sep($line);
                   11113:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      11114:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   11115:         if ($entries[1] eq 'Response') { $skipline=1; }
                   11116:         next if $skipline;
                   11117:         if ($entries[0]!=$questionnumber) {
                   11118:            $questionnumber=$entries[0];
                   11119:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   11120:            $number++;
1.419     www      11121:         }
1.420     www      11122:         my $id=$entries[4];
                   11123:         $id=~s/^[\#0]+//;
1.421     www      11124:         $id=~s/^v\d*\://i;
                   11125:         $id=~s/[\-\:]//g;
1.420     www      11126:         $idresponses{$id}[$number]=$entries[6];
                   11127:     }
1.524     raeburn  11128:     foreach my $id (keys(%idresponses)) {
1.420     www      11129:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   11130:        $$responses{$id}=~s/^\s*\,//;
1.419     www      11131:     }
                   11132:     return ($errormsg,$number);
                   11133: }
                   11134: 
1.666     www      11135: sub turning_eval {
                   11136:     my ($questiontitles,$responses)=@_;
                   11137:     my $number=0;
                   11138:     my $errormsg='';
                   11139:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   11140:         my %components=&Apache::loncommon::record_sep($line);
                   11141:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   11142:         if ($#entries>$number) { $number=$#entries; }
                   11143:         my $id=$entries[0];
                   11144:         my @idresponses;
                   11145:         $id=~s/^[\#0]+//;
                   11146:         unless ($id) { next; }
                   11147:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   11148:             $entries[$idx]=~s/\,/\;/g;
                   11149:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   11150:             push(@idresponses,$entries[$idx]);
                   11151:         }
                   11152:         $$responses{$id}=join(',',@idresponses);
                   11153:     }
                   11154:     for (my $i=1; $i<=$number; $i++) {
                   11155:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   11156:     }
                   11157:     return ($errormsg,$number);
                   11158: }
                   11159: 
                   11160: 
1.414     www      11161: sub assign_clicker_grades {
1.766     raeburn  11162:     my ($r,$symb) = @_;
1.414     www      11163:     if (!$symb) {return '';}
1.416     www      11164: # See which part we are saving to
1.582     raeburn  11165:     my $res_error;
                   11166:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   11167:     if ($res_error) {
                   11168:         return &navmap_errormsg();
                   11169:     }
1.416     www      11170: # FIXME: This should probably look for the first handgradeable part
                   11171:     my $part=$$partlist[0];
                   11172: # Start screen output
1.766     raeburn  11173:     my $result = &Apache::loncommon::start_data_table().
                   11174:                  &Apache::loncommon::start_data_table_header_row().
                   11175:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   11176:                  &Apache::loncommon::end_data_table_header_row().
                   11177:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11178: # Get correct result
                   11179: # FIXME: Possibly need delimiter other than ":"
                   11180:     my @correct=();
1.415     www      11181:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11182:     my $number=$env{'form.number'};
                   11183:     if ($gradingmechanism ne 'attendance') {
1.414     www      11184:        foreach my $key (keys(%env)) {
                   11185:           if ($key=~/^form\.correct\:/) {
                   11186:              my @input=split(/\,/,$env{$key});
                   11187:              for (my $i=0;$i<=$#input;$i++) {
                   11188:                  if (($correct[$i]) && ($input[$i]) &&
                   11189:                      ($correct[$i] ne $input[$i])) {
                   11190:                     $result.='<br /><span class="LC_warning">'.
                   11191:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11192:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11193:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11194:                     $correct[$i]=$input[$i];
                   11195:                  }
                   11196:              }
                   11197:           }
                   11198:        }
1.415     www      11199:        for (my $i=0;$i<$number;$i++) {
1.644     www      11200:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11201:              $result.='<br /><span class="LC_error">'.
                   11202:                       &mt('No correct result given for question "[_1]"!',
                   11203:                           $env{'form.question:'.$i}).'</span>';
                   11204:           }
                   11205:        }
1.644     www      11206:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11207:     }
                   11208: # Start grading
1.415     www      11209:     my $pcorrect=$env{'form.pcorrect'};
                   11210:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11211:     my $storecount=0;
1.632     www      11212:     my %users=();
1.415     www      11213:     foreach my $key (keys(%env)) {
1.420     www      11214:        my $user='';
1.415     www      11215:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11216:           $user=$1;
                   11217:        }
                   11218:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11219:           my $id=$1;
                   11220:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11221:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11222:           } elsif ($env{'form.multi'.$id}) {
                   11223:              $user=$env{'form.multi'.$id};
1.420     www      11224:           }
                   11225:        }
1.632     www      11226:        if ($user) {
                   11227:           if ($users{$user}) {
                   11228:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11229:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11230:                       '</span><br />';
                   11231:           }
                   11232:           $users{$user}=1; 
1.415     www      11233:           my @answer=split(/\,/,$env{$key});
                   11234:           my $sum=0;
1.522     www      11235:           my $realnumber=$number;
1.415     www      11236:           for (my $i=0;$i<$number;$i++) {
1.576     www      11237:              if  ($correct[$i] eq '-') {
                   11238:                 $realnumber--;
1.766     raeburn  11239:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11240:                 if ($gradingmechanism eq 'attendance') {
                   11241:                    $sum+=$pcorrect;
1.576     www      11242:                 } elsif ($correct[$i] eq '*') {
1.522     www      11243:                    $sum+=$pcorrect;
1.415     www      11244:                 } else {
1.644     www      11245: # We actually grade if correct or not
                   11246:                    my $increment=$pincorrect;
                   11247: # Special case: numerical answer "0"
                   11248:                    if ($correct[$i] eq '0') {
                   11249:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11250:                          $increment=$pcorrect;
                   11251:                       }
                   11252: # General numerical answer, both evaluate to something non-zero
                   11253:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11254:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11255:                          $increment=$pcorrect;
                   11256:                       }
                   11257: # Must be just alphanumeric
                   11258:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11259:                       $increment=$pcorrect;
1.415     www      11260:                    }
1.644     www      11261:                    $sum+=$increment;
1.415     www      11262:                 }
                   11263:              }
                   11264:           }
1.522     www      11265:           my $ave=$sum/(100*$realnumber);
1.416     www      11266: # Store
                   11267:           my ($username,$domain)=split(/\:/,$user);
                   11268:           my %grades=();
                   11269:           $grades{"resource.$part.solved"}='correct_by_override';
                   11270:           $grades{"resource.$part.awarded"}=$ave;
                   11271:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11272:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11273:                                                  $env{'request.course.id'},
                   11274:                                                  $domain,$username);
                   11275:           if ($returncode ne 'ok') {
                   11276:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11277:           } else {
                   11278:              $storecount++;
                   11279:           }
1.415     www      11280:        }
                   11281:     }
                   11282: # We are done
1.549     hauer    11283:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11284:              '</td>'.
                   11285:              &Apache::loncommon::end_data_table_row().
                   11286:              &Apache::loncommon::end_data_table();
1.614     www      11287:     return $result;
1.414     www      11288: }
                   11289: 
1.582     raeburn  11290: sub navmap_errormsg {
                   11291:     return '<div class="LC_error">'.
                   11292:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11293:            &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  11294:            '</div>';
                   11295: }
1.607     droeschl 11296: 
1.609     www      11297: sub startpage {
1.773   ! raeburn  11298:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload,$divforres) = @_;
1.754     raeburn  11299:     my %args;
                   11300:     if ($onload) {
                   11301:          my %loaditems = (
                   11302:                         'onload' => $onload,
                   11303:                       );
                   11304:          $args{'add_entries'} = \%loaditems;
                   11305:     }
1.671     raeburn  11306:     if ($nomenu) {
1.754     raeburn  11307:         $args{'only_body'} = 1; 
1.759     raeburn  11308:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
1.671     raeburn  11309:     } else {
                   11310:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11311:         $args{'bread_crumbs'} = $crumbs;
                   11312:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.765     raeburn  11313:         if ($env{'request.course.id'}) {
                   11314:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11315:         }
1.671     raeburn  11316:     }
1.613     www      11317:     unless ($nodisplayflag) {
1.773   ! raeburn  11318:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp,$divforres));
1.613     www      11319:     }
1.607     droeschl 11320: }
1.582     raeburn  11321: 
1.622     www      11322: sub select_problem {
                   11323:     my ($r)=@_;
1.632     www      11324:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771     raeburn  11325:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11326:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11327:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11328: }
                   11329: 
1.1       albertel 11330: sub handler {
1.41      ng       11331:     my $request=$_[0];
1.434     albertel 11332:     &reset_caches();
1.646     raeburn  11333:     if ($request->header_only) {
                   11334:         &Apache::loncommon::content_type($request,'text/html');
                   11335:         $request->send_http_header;
                   11336:         return OK;
                   11337:     }
                   11338:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11339: 
1.664     raeburn  11340: # see what command we need to execute
                   11341: 
                   11342:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11343:     my $command=$commands[0];
                   11344: 
1.646     raeburn  11345:     &init_perm();
                   11346:     if (!$env{'request.course.id'}) {
1.664     raeburn  11347:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11348:                 ($command =~ /^scantronupload/)) {
                   11349:             # Not in a course.
                   11350:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11351:             return HTTP_NOT_ACCEPTABLE;
                   11352:         }
1.646     raeburn  11353:     } elsif (!%perm) {
                   11354:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11355:         return OK;
1.41      ng       11356:     }
1.646     raeburn  11357:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11358:     $request->send_http_header;
1.646     raeburn  11359: 
1.160     albertel 11360:     if ($#commands > 0) {
                   11361: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11362:     }
1.608     www      11363: 
                   11364: # see what the symb is
                   11365: 
                   11366:     my $symb=$env{'form.symb'};
                   11367:     unless ($symb) {
                   11368:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11369:        $symb=&Apache::lonnet::symbread($url);
                   11370:     }
1.646     raeburn  11371:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11372: 
1.513     foxr     11373:     $ssi_error = 0;
1.637     www      11374:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11375: #
1.637     www      11376: # Not called from a resource, but inside a course
1.601     www      11377: #    
1.622     www      11378:         &startpage($request,undef,[],1,1);
                   11379:         &select_problem($request);
1.41      ng       11380:     } else {
1.104     albertel 11381: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.773   ! raeburn  11382:             my ($stuvcurrent,$stuvdisp,$versionform,$js,$onload);
1.671     raeburn  11383:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11384:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11385:                     &choose_task_version_form($symb,$env{'form.student'},
                   11386:                                               $env{'form.userdom'});
                   11387:             }
1.773   ! raeburn  11388:             my $divforres;
        !          11389:             if ($env{'form.student'} eq '') {
        !          11390:                 $js .= &part_selector_js();
        !          11391:                 $onload = "toggleParts('gradesub');";
        !          11392:             } else {
        !          11393:                 $divforres = 1;
        !          11394:             }
        !          11395:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js,$onload,$divforres);
1.671     raeburn  11396:             if ($versionform) {
                   11397:                 $request->print($versionform);
                   11398:             }
1.773   ! raeburn  11399: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb,'',$divforres) : &submission($request,0,0,$symb,$divforres,$command));
1.671     raeburn  11400:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11401:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11402:                 &choose_task_version_form($symb,$env{'form.student'},
                   11403:                                           $env{'form.userdom'},
                   11404:                                           $env{'form.inhibitmenu'});
                   11405:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   11406:             if ($versionform) {
                   11407:                 $request->print($versionform);
                   11408:             }
                   11409:             $request->print('<br clear="all" />');
                   11410:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11411: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11412:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11413:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11414: 	    &pickStudentPage($request,$symb);
1.103     albertel 11415: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      11416:             &startpage($request,$symb,
                   11417:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11418:                                        {href=>'',text=>'Select student'},
                   11419:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      11420: 	    &displayPage($request,$symb);
1.104     albertel 11421: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11422:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11423:                                        {href=>'',text=>'Select student'},
                   11424:                                        {href=>'',text=>'Grade student'},
                   11425:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11426: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11427: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      11428:             &startpage($request,$symb,[{href=>'',text=>'...'},
1.773   ! raeburn  11429:                                        {href=>'',text=>'Modify grades'}],undef,undef,undef,undef,undef,undef,undef,1);
1.608     www      11430: 	    &processGroup($request,$symb);
1.104     albertel 11431: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11432:             &startpage($request,$symb);
                   11433: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11434: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11435:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11436: 	    $request->print(&submit_options($request,$symb));
1.598     www      11437:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.773   ! raeburn  11438:             my $js = &part_selector_js();
        !          11439:             my $onload = "toggleParts('gradesub');";
        !          11440:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}],
        !          11441:                        undef,undef,undef,undef,undef,$js,$onload);
1.617     www      11442:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11443:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11444:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11445:             $request->print(&submit_options_table($request,$symb));
1.598     www      11446:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11447:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11448:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11449: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11450:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11451: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11452: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11453:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11454:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11455: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11456: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11457:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11458:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11459:                                                                              text=>"Modify grades"},
                   11460:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11461: 	    $request->print(&editgrades($request,$symb));
1.602     www      11462:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11463:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11464:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11465: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11466:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11467:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11468: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11469:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11470:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11471:             $request->print(&process_clicker($request,$symb));
1.400     www      11472:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11473:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11474:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11475:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11476:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11477:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11478:                                        {href=>'', text=>'Process clicker file'},
                   11479:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11480:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11481: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11482:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11483: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11484: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11485:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11486: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11487: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11488:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11489: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11490: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11491: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11492:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11493: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11494: 	    } else {
1.257     albertel 11495: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11496: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11497: 		} else {
1.257     albertel 11498: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11499: 		}
1.627     www      11500:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11501: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11502: 	    }
1.246     albertel 11503: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11504:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11505: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11506: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11507:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11508:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11509: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11510:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11511:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11512:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11513: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11514:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11515: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11516: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11517:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11518: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11519:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11520:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11521:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11522:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11523:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11524:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11525:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11526:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11527:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11528:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11529:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11530:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11531:         } elsif ($command eq 'scantronupload_delete' &&
                   11532:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11533:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11534:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11535:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11536:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11537:             $request->print(&checkscantron_results($request,$symb));
                   11538:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
1.773   ! raeburn  11539:             my $js = &part_selector_js();
        !          11540:             my $onload = "toggleParts('gradingMenu');";
        !          11541:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}],
        !          11542:                        undef,undef,undef,undef,undef,$js,$onload);
1.621     www      11543:             $request->print(&submit_options_download($request,$symb));
                   11544:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11545:             &startpage($request,$symb,
                   11546:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.773   ! raeburn  11547:     {href=>'', text=>'Download submitted files'}],
        !          11548:                undef,undef,undef,undef,undef,undef,undef,1);
1.621     www      11549:             &submit_download_link($request,$symb);
1.106     albertel 11550: 	} elsif ($command) {
1.620     www      11551:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11552: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11553: 	}
1.2       albertel 11554:     }
1.513     foxr     11555:     if ($ssi_error) {
                   11556: 	&ssi_print_error($request);
                   11557:     }
1.671     raeburn  11558:     if ($env{'form.inhibitmenu'}) {
                   11559:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11560:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11561:         &Apache::lonquickgrades::endGradeScreen($request);
                   11562:     }
1.434     albertel 11563:     &reset_caches();
1.646     raeburn  11564:     return OK;
1.44      ng       11565: }
                   11566: 
1.1       albertel 11567: 1;
                   11568: 
1.13      albertel 11569: __END__;
1.531     jms      11570: 
                   11571: 
                   11572: =head1 NAME
                   11573: 
                   11574: Apache::grades
                   11575: 
                   11576: =head1 SYNOPSIS
                   11577: 
                   11578: Handles the viewing of grades.
                   11579: 
                   11580: This is part of the LearningOnline Network with CAPA project
                   11581: described at http://www.lon-capa.org.
                   11582: 
                   11583: =head1 OVERVIEW
                   11584: 
                   11585: Do an ssi with retries:
1.715     bisitz   11586: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11587: 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
                   11588: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11589: 
                   11590: At least the logic that drives this has been pulled out into loncommon.
                   11591: 
                   11592: 
                   11593: 
                   11594: ssi_with_retries - Does the server side include of a resource.
                   11595:                      if the ssi call returns an error we'll retry it up to
                   11596:                      the number of times requested by the caller.
1.715     bisitz   11597:                      If we still have a problem, no text is appended to the
1.531     jms      11598:                      output and we set some global variables.
                   11599:                      to indicate to the caller an SSI error occurred.  
                   11600:                      All of this is supposed to deal with the issues described
1.715     bisitz   11601:                      in LON-CAPA BZ 5631 see:
1.531     jms      11602:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11603:                      by informing the user that this happened.
                   11604: 
                   11605: Parameters:
                   11606:   resource   - The resource to include.  This is passed directly, without
                   11607:                interpretation to lonnet::ssi.
                   11608:   form       - The form hash parameters that guide the interpretation of the resource
                   11609:                
                   11610:   retries    - Number of retries allowed before giving up completely.
                   11611: Returns:
                   11612:   On success, returns the rendered resource identified by the resource parameter.
                   11613: Side Effects:
                   11614:   The following global variables can be set:
                   11615:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11616:                               It is up to the caller to initialize this to false
                   11617:                               if desired.
                   11618:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11619:                               of the resource that could not be rendered by the ssi
                   11620:                               call.
                   11621:    ssi_error_message   - The error string fetched from the ssi response
                   11622:                               in the event of an error.
                   11623: 
                   11624: 
                   11625: =head1 HANDLER SUBROUTINE
                   11626: 
                   11627: ssi_with_retries()
                   11628: 
                   11629: =head1 SUBROUTINES
                   11630: 
                   11631: =over
                   11632: 
1.671     raeburn  11633: =head1 Routines to display previous version of a Task for a specific student
                   11634: 
                   11635: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11636: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11637: requires a proctor to check-in the student, a new version of the Task will
                   11638: be created when the student is checked in to the new opportunity.
                   11639: 
                   11640: If a particular student has tried two or more versions of a particular task,
                   11641: the submission screen provides a user with vgr privileges (e.g., a Course
                   11642: Coordinator) the ability to display a previous version worked on by the
                   11643: student.  By default, the current version is displayed. If a previous version
                   11644: has been selected for display, submission data are only shown that pertain
                   11645: to that particular version, and the interface to submit grades is not shown.
                   11646: 
                   11647: =over 4
                   11648: 
                   11649: =item show_previous_task_version()
                   11650: 
                   11651: Displays a specified version of a student's Task, as the student sees it.
                   11652: 
                   11653: Inputs: 2
                   11654:         request - request object
                   11655:         symb    - unique symb for current instance of resource
                   11656: 
                   11657: Output: None.
                   11658: 
                   11659: Side Effects: calls &show_problem() to print version of Task, with
                   11660:               version contained in form item: $env{'form.previousversion'}
                   11661: 
                   11662: =item choose_task_version_form()
                   11663: 
                   11664: Displays a web form used to select which version of a student's view of a
                   11665: Task should be displayed.  Either launches a pop-up window, or replaces
                   11666: content in existing pop-up, or replaces page in main window.
                   11667: 
                   11668: Inputs: 4
                   11669:         symb    - unique symb for current instance of resource
                   11670:         uname   - username of student
                   11671:         udom    - domain of student
                   11672:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11673:                   breadcrumbs etc., are displayed
                   11674: 
                   11675: Output: 4
                   11676:         current   - student's current version
                   11677:         displayed - student's version being displayed
                   11678:         result    - scalar containing HTML for web form used to switch to
                   11679:                     a different version (or a link to close window, if pop-up).
                   11680:         js        - javascript for processing selection in versions web form
                   11681: 
                   11682: Side Effects: None.
                   11683: 
                   11684: =item previous_display_javascript()
                   11685: 
                   11686: Inputs: 2
                   11687:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11688:                   breadcrumbs etc., are displayed.
                   11689:         current - student's current version number.
                   11690: 
                   11691: Output: 1
                   11692:         js      - javascript for processing selection in versions web form.
                   11693: 
                   11694: Side Effects: None.
                   11695: 
                   11696: =back
                   11697: 
                   11698: =head1 Routines to process bubblesheet data.
                   11699: 
                   11700: =over 4
                   11701: 
1.531     jms      11702: =item scantron_get_correction() : 
                   11703: 
                   11704:    Builds the interface screen to interact with the operator to fix a
                   11705:    specific error condition in a specific scanline
                   11706: 
                   11707:  Arguments:
                   11708:     $r           - Apache request object
                   11709:     $i           - number of the current scanline
                   11710:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11711:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11712:     $line        - full contents of the current scanline
                   11713:     $error       - error condition, valid values are
                   11714:                    'incorrectCODE', 'duplicateCODE',
                   11715:                    'doublebubble', 'missingbubble',
                   11716:                    'duplicateID', 'incorrectID'
                   11717:     $arg         - extra information needed
                   11718:        For errors:
                   11719:          - duplicateID   - paper number that this studentID was seen before on
                   11720:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11721:                            seen on before
                   11722:          - incorrectCODE - current incorrect CODE 
                   11723:          - doublebubble  - array ref of the bubble lines that have double
                   11724:                            bubble errors
                   11725:          - missingbubble - array ref of the bubble lines that have missing
                   11726:                            bubble errors
                   11727: 
1.691     raeburn  11728:    $randomorder - True if exam folder has randomorder set
                   11729:    $randompick  - True if exam folder has randompick set
                   11730:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11731:                      for current line to question number used for same question
                   11732:                      in "Master Seqence" (as seen by Course Coordinator).
                   11733:    $startline   - Reference to hash where key is question number (0 is first)
                   11734:                   and value is number of first bubble line for current student
                   11735:                   or code-based randompick and/or randomorder.
                   11736: 
                   11737: 
                   11738: 
1.531     jms      11739: =item  scantron_get_maxbubble() : 
                   11740: 
1.582     raeburn  11741:    Arguments:
                   11742:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11743:                       failure to retrieve a navmap object.
                   11744:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11745:        calling routine should trap the error condition and display the warning
                   11746:        found in &navmap_errormsg().
                   11747: 
1.649     raeburn  11748:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11749: 
1.531     jms      11750:    Returns the maximum number of bubble lines that are expected to
                   11751:    occur. Does this by walking the selected sequence rendering the
                   11752:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11753:    for what the current value of the problem counter is.
                   11754: 
                   11755:    Caches the results to $env{'form.scantron_maxbubble'},
                   11756:    $env{'form.scantron.bubble_lines.n'}, 
                   11757:    $env{'form.scantron.first_bubble_line.n'} and
                   11758:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11759:    which are the total number of bubble lines, the number of bubble
1.531     jms      11760:    lines for response n and number of the first bubble line for response n,
                   11761:    and a comma separated list of numbers of bubble lines for sub-questions
                   11762:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11763: 
                   11764: 
                   11765: =item  scantron_validate_missingbubbles() : 
                   11766: 
                   11767:    Validates all scanlines in the selected file to not have any
                   11768:     answers that don't have bubbles that have not been verified
                   11769:     to be bubble free.
                   11770: 
                   11771: =item  scantron_process_students() : 
                   11772: 
1.659     raeburn  11773:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11774: 
                   11775:    The parsed scanline hash is added to %env 
                   11776: 
                   11777:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11778:    foreach resource , with the form data of
                   11779: 
                   11780: 	'submitted'     =>'scantron' 
                   11781: 	'grade_target'  =>'grade',
                   11782: 	'grade_username'=> username of student
                   11783: 	'grade_domain'  => domain of student
                   11784: 	'grade_courseid'=> of course
                   11785: 	'grade_symb'    => symb of resource to grade
                   11786: 
                   11787:     This triggers a grading pass. The problem grading code takes care
                   11788:     of converting the bubbled letter information (now in %env) into a
                   11789:     valid submission.
                   11790: 
                   11791: =item  scantron_upload_scantron_data() :
                   11792: 
1.659     raeburn  11793:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11794: 
                   11795: =item  scantron_upload_scantron_data_save() : 
                   11796: 
                   11797:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11798:    has the correct privileges to do so.
                   11799: 
                   11800: = item scantron_upload_delete() :
                   11801: 
                   11802:    Deletes a previously uploaded bubble information data file, if user
                   11803:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11804: 
                   11805: =item  valid_file() :
                   11806: 
                   11807:    Validates that the requested bubble data file exists in the course.
                   11808: 
                   11809: =item  scantron_download_scantron_data() : 
                   11810: 
                   11811:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11812:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11813:    course.
                   11814: 
                   11815: =item  scantron_validate_ID() : 
                   11816: 
                   11817:    Validates all scanlines in the selected file to not have any
1.556     weissno  11818:    invalid or underspecified student/employee IDs
1.531     jms      11819: 
1.582     raeburn  11820: =item navmap_errormsg() :
                   11821: 
                   11822:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11823:    Should be called whenever the request to instantiate a navmap object fails.
                   11824: 
                   11825: =back
1.582     raeburn  11826: 
1.531     jms      11827: =back
                   11828: 
                   11829: =cut

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